Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings in C++ 04/29/11. Quiz Arrays  Section 7.1 & 7.2  Array basics  Partially filled arrays  Passing individual elements Mon. 05/02/11.

Similar presentations


Presentation on theme: "Strings in C++ 04/29/11. Quiz Arrays  Section 7.1 & 7.2  Array basics  Partially filled arrays  Passing individual elements Mon. 05/02/11."— Presentation transcript:

1 Strings in C++ 04/29/11

2 Quiz Arrays  Section 7.1 & 7.2  Array basics  Partially filled arrays  Passing individual elements Mon. 05/02/11

3 C-Strings Old version from the C language Arrays of Characters cout <”Hello”; -------------------------------- |'H'|'e'|'l'|'l'|'o'|\0|...| ---------------------------- Null character, \0, marks end of string

4 C-Strings Can initialize  Cannot assign  To Copy, use strcpy() function. In cstring library copyEr.cpp  Attempts an assignment copyCstring.c  Uses strcpy()

5 string class const string COLOR = “Green”; New type in C++  string is new type  C-string is old type string.cpp  Input reads to blank  Does allow assignments.

6 Conversion of string C-string = string constructor automatically converts C- string to string. string word; word = “fish”; char name[20]; name = word; //ERROR, NO //string to C-string // Conversion

7 Conversion of string C-string Some functions require C-string arguments. ifstream infile( filename);  Filename must be C-string .c_str() function does conversion writefile.cpp  Compiler error  Can fix with.c_str

8 getline string str; cin >> str; Reads up to white space. getline reads in whole line. sentence.cpp Syntax:  getline(inputStream, string,delimiter);  Default delimiter is '\n'  Delimiter not read into string

9 get Gets one character ifstream ins(“data.txt”); char c; ins.get(c);

10 More String Operations(p. 300)‏ Compare with ==, <=, etc Copy with = Concatenate with + string msg; msg = “Hello, “; msg = msg + “Class.\n” at msg.at(4) --> 'o' Some used in winner.cpp

11 Questions How many chars does it take to store “Kate” as a C-string? What does the following statement sequence print? string str = “Harry”; cout << str.at(0) << str.at(1); Give an input statement to read a name of the form “John Q. Public”.

12 Next Time Dynamic Arrays, Monday Read pp. 313-320 Then Friday review for the final.


Download ppt "Strings in C++ 04/29/11. Quiz Arrays  Section 7.1 & 7.2  Array basics  Partially filled arrays  Passing individual elements Mon. 05/02/11."

Similar presentations


Ads by Google