morteza noferesti no explicit type instead strings are
play

Morteza Noferesti No explicit type, instead strings are maintained - PowerPoint PPT Presentation

Morteza Noferesti No explicit type, instead strings are maintained as arrays of characters Representing strings in C stored in arrays of characters array can be of any length end of string is indicated by a delimiter , the zero


  1. Morteza Noferesti

  2.  No explicit type, instead strings are maintained as arrays of characters  Representing strings in C ◦ stored in arrays of characters ◦ array can be of any length ◦ end of string is indicated by a delimiter , the zero character ‘ \0 ’ " A S t r in g " A S t r i n g \ 0

  3.  String literal values are represented by sequences of characters between double quotes (“)  Examples ◦ “” - empty string ◦ “hello”  “a” versus ‘a’ ◦ ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a ◦ “a” is an array with two characters, the first is a, the second is the character value \0 3

  4.  String literal is an array, can refer to a single character from the literal as a character  Example: printf (“%c”,”hello”[ 1]); outputs the character ‘e’  During compilation, C creates space for each string literal (# of characters in the literal + 1) ◦ referring to the literal refers to that space (as if it is an array) 4

  5.  Each string literal in a C program is stored at a different location  So even if the string literals contain the same string, they are not equal (in the == sense)  Example: ◦ char string1[6 ] = “hello”; ◦ char string2[6 ] = “hello”; ◦ but string1 does not equal string2 (they are stored at different locations) 5

  6.  Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter)  Examples (with initialization): char str1[6 ] = “Hello”; char str2 [] = “Hello”; char *str3 = “Hello”; char str4[6 ] = {‘H’,’e’,’l’,’l’,’o’,’ \0 ’};  Note, each variable is considered a constant in that the space it is connected to cannot be changed str1 = str2; /* not allowable, but we can copy the contents of str2 to str1 (more later) */ 6

  7.  Can change parts of a string variable char str1[6 ] = “hello”; str1[0 ] = ‘y’; /* str1 is now “ yello ” */ str1[4 ] = ‘ \0 ’; /* str1 is now “yell” */  Important to retain delimiter (replacing str1[5] in the original string with something other than ‘ \0 ’ makes a string that does not end)  Have to stay within limits of array 7

  8.  Use %s field specification in scanf to read string ◦ ignores leading white space ◦ reads characters until next white space encountered ◦ C stores null (\0) char after last non-white space char ◦ Reads into array (no & before name, array is a pointer)  Example: char Name[11]; scanf (“%s”,Name );  Problem: no limit on number of characters read (need one for delimiter), if too many characters for array, problems may occur 8

  9. char *str, s[] = "ALIREZA"; printf("%s", s); // ALIREZA printf(s) ; // ALIREZA printf("%s", s + 3); // REZA scanf("%s", s); scanf("%s", &s[0]); 9

  10. char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };  suit[0] H e a r t s \0  suit[1] D i a m o n d s \0  suit[2] C l u b s \0  suit[3] S p a d e s \0 10

  11. Empty string ""  ◦ Is not null pointer ◦ Is not uninitialized pointer 11

  12.  Can use the width value in the field specification to limit the number of characters read: char Name[11]; scanf (“% 10 s”,Name);  Remember, you need one space for the \0 ◦ width should be one less than size of array  Strings shorter than the field specification are read normally, but C always stops after reading 10 characters 12

  13. #include <stdio.h> void main() { char LastName[11]; char FirstName[11]; printf("Enter your name "); scanf("%10s",FirstName); printf("Nice to meet you %s\n", FirstName); } 13

  14.  char *gets(char *str)  reads the next line (up to the next newline) from keyboard and stores it in the array of chars pointed to by str  returns str if string read or NULL if problem/end-of-file  not limited in how many chars read (may read too many for array)  newline included in string read 14

  15.  int puts(char *str)  prints the string pointed to by str to the screen  prints until delimiter reached (string better have a \0)  returns EOF if the puts fails  outputs newline if \n encountered (for strings read with gets ) 15

  16. #include <stdio.h> int main() { char str[50]; printf("Enter a string : "); gets(str); puts(str); return(0); } 16

  17.  C provides a wide range of string functions for performing different string tasks  Examples strlen(str) - calculate string length strcpy(dst,src) - copy string at src to dst strcmp(str1,str2) - compare str1 to str2  Functions come from the utility library string.h ◦ #include <string.h> 17

  18. Files 18

  19.  A file is a collection of related data that a computers treats as a single unit.  When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device.  C uses a structure called FILE (defined in stdio.h ) to store the attributes of a file. 19

  20.  Until now  We read/write data from/to terminal (console)  In C  We can read data from file  We can write data to file 20

  21.  Main steps in working with files  1) Open file  Get a file handler from Operating System  2) Read/Write  Use the handler  3) Close file  Free the handler  4) Other operations Check end of file, …  21

  22.  Function fopen opens files #include <stdio.h> FILE * fopen(char *name, char *mode);  FILE * is struct  Saves information about file.  We don’t need to know about it.  If cannot open file, fopen returns NULL.  name is the name of file:  Absolute name: C:\prog\test.txt  Relative name: Mytest.txt 22

  23.  r: open for read. We cannot write to the file.  w: open for write. Create new file. We cannot read form the file. If file exist, its content will be destroyed.  a: open for write. We cannot read form the file. If file exist, its content wont be destroyed. We write at end of file. 23

  24. fopen Returns if FILE- Mode Meaning Exists Not Exists – r Reading NULL w Writing Over write on Existing Create New File – a Append Create New File New data is written at the Reading + r+ beginning overwriting Create New File Writing existing data Reading + w+ Over write on Existing Create New File Writing Reading + New data is appended at a+ Create New File Appending the end of file 24

  25. FILE *fp; fp = fopen("c:\test.txt", "r"); if(fp == NULL){ printf("Cannot open file\n"); return -1; }  Open file c:\test.txt for read 25

  26.  File-Position Pointer  A pointer in file  Points to current location of read and write  When file is open  File-Position Pointer is set to start of file  When you read/write from/to file  The File-Position Pointer advance according to the size of data  If you read 2 bytes, it moves 2 bytes  If you write 50 bytes, it advances 50 bytes 26

  27.  Each opened file should be closed.  If we write to a file and don’t close it, some of data will be LOST  To close the file fclose(FILE *fp); 27

  28.  fscanf reads from file  fscanf is same to scanf. Return EOF if reached  fprintf writes to file  fprintf is same to printf. int fscanf(FILE *fp,"format", parameters); int fprintf(FILE *fp,"format", parameters); 28

  29.  We have file in this format <Number of students> <id of student 1> <grade of student 1> <id of student 2> <grade of student 2> … <id of student n> <grade of student n> 29

  30. #include <stdio.h> ‌هرمن‌و‌هرامش‌هك‌يا‌همانرب دناوخب‌لياف‌زا‌ار‌نايوجشناد‌و #include <stdlib.h> دنك‌هبساحم‌ار‌نيگنايم . int main(void){ FILE *fpin; char inname[20]; int num, i, id; float sum, average, grade; printf("Enter the name of input file: "); scanf("%s", inname); fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; } 30

  31. /* Read the number of students */ fscanf(fpin,"%d", &num); /* Read the id and grade from file */ sum = 0; for(i = 0; i < num; i++){ fscanf(fpin, "%d %f", &id, &grade); sum += grade; } average = sum / num; printf("Average = %f\n", average); fclose(fpin); return 0; } 31

  32. #include <stdio.h> ر‌نايوجشناد‌هرمن‌و‌هرامش‌هك‌يا‌همانرب‌ا #include <stdlib.h> ك‌ينايوجشناد‌تسيل‌و‌دناوخب‌لياف‌زا‌ه ار‌تسا‌نيگنايم‌زا‌رتشيب‌اهنآ‌هرمن‌رد دسيونب‌يرگيد‌لياف . int main(void){ FILE *fpin, *fpout; char inname[20], outname[20]; int num, i, id; float sum, average, grade; printf("Enter the name of input file: "); scanf("%s", inname); printf("Enter the name of output file: "); scanf("%s", outname); fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; } 32

Recommend


More recommend