C Strings Strings Big improvement on C strings
C++ Strings
Strings • Big improvement on C "strings" • Sequence of characters – Can be empty sequence • Strings are mutable in C++ (can be changed) – Not same as literal or char * (but implicit conversion can be done) #include<string> string s = "hello"; // implicit conversion
String Indexing • string s = "hi ya!"; index 0 1 2 3 4 5 character 'h' 'i' '' 'y' 'a' '!' • Two ways to access characters in string: – char c 1 = s[3]; // 'y' – char c 2 = s. at(1); // 'i' • Recall that characters have ASCII encodings: cout << (int) 'B' << endl; // 66
String Operations • Concatenate strings with +: string s = "Hello"; // "Hello World" • Compare strings with relational operators: string s 2 = "Hi"; if(s 1 < s 2 && s 2 != "Bye") { // true. . . } • Add and change characters in strings: string s 1 = s + " World"; string s 1 = "Mary"; s 1. append(" Eberlein"); // "Mary Eberlein" s 1. erase(1, 3); // "M Eberlein" s 1[1] = 'e'; // "Me. Eberlein"
String Operations • s. insert(index, str): add str to s at specified index • string s = "hello world!"; • s. insert(5, " to the"); // "hello to the world!"
String Comparison • string str 1 =. . . ; string str 2 =. . . ; • if(str 1 == str 2) • if(str 1 < str 2) // compares characters // compares in dictionary order
Member Functions Function Name Description s. append(str) Add str to end of string s s. compare(str) Returns -1, 0, or 1 depending on relative ordering of s and str s. erase(index, len) Delete len characters of s starting at specified index s. find(str) s. rfind(str) Returns first or last index where str appears in s (or string: : npos if not found) s. length() or s. size() Returns number of characters in string s. replace(index, len, str) Replaces len chars at given index with str s. substr(start, len) s. substr(start) Returns next len chars beginning at start index If len omitted, goes to end of string greeting = "hello world"; if(greeting. find("hello") != string: : npos) { greeting. erase(0, 6); // "world" }
Question What's the output? void mystery(string a, string& b) { a. erase(0, 1); // erase 1 from index 0 b += a[0]; b. insert(3, "FOO"); // insert at index 3 } int main() { string a = "mary"; string b = "eberlein"; mystery(a, b); cout << a << " " << b << endl; return 0; }
C++ Strings vs. C Strings! • C++ has two kinds of strings: – C strings, which are char arrays – C++ strings which are string objects • Use these! • Ugh: a string literal like "hello" is a C string – Can't use member functions – Ex: ("hello"). length() // syntax error – Ex: string s = "hello"; len = s. length(); // 5 – Ex: string s = "hello" + " world"; // error – Ex: string s = "hello"; string t = " world"; string u = s + t; // works! • Conversions: – string("str") // converts "str" to a C++ string – string. c_str() // returns C string version of the string
Example • string s = "hi"; s = s + 41; // error • To build a string from values of different types, use a stringstream – outputs data to a string – call. str() on stringstream to extract as a string #include <sstream> stringstream; stream << s << " " << 41; s = stream. str(); cout << s; // prints: hi 41
Reading Strings • cin reads strings one word at a time string name; cout << "Enter your name, please: "; //Anna Banana cin >> name; cout << "Hello, " << name << endl; // Hello, Anna • getline reads entire line at once string name; cout << "Enter your name, please: "; getline(cin, name); cout << "Hello, " << name << endl; Output: Hello, Anna Banana
I/O Streams STANDARD AND FILE I/O
I/O Streams COMMAND cout << expression HOW IT WORKS Output extraction operator Writes expression to stdout cin >> var input insertion operator Reads value from stdin and stores in var • data sent in direction of arrow • endl: like 'n' and flushes stream • Use cin to read values, or getline to read entire line
Formatting with <iomanip> • #include<iomanip> • formatted output similar to printf • Functions: – setw(n): set width of next field to be printed – setprecision(p): set precision in decimal places of next field – Others: setfill, setbase, etc. • Can also use printf cout << "You are " << setw(4) << age << " years. " << endl;
File I/O • #include<fstream> – ifstream, ofstream classes for input, output files • cin – variable of type ifstream • cout – variable of type ofstream • Typical pattern: – open file, read every line from file, close file ifstream input; input. open("good. Stuff. txt"); // Open the file string line; while(getline(input, line)) { // Read every line cout << line << endl; } input. close(); // close file
ifstream functions Function Description stream. fail() Returns true if last read call failed (e. g. , EOF) stream. open(filename) opens file represented by specified C string stream. close() stream. get(var) Reads and returns one character Reads next char into var - returns EOF when end of file reached getline(f&, str&) Reads line of input into str. Returns true on success, false on failure. f >> var Read data from input file into var
Example • What does this do? while(!input. fail()) { getline(input, line); cout << line << endl; }
ofstream functions function stream << expression description stream. put(ch) Writes character to output stream writes expression to output stream ofstream output; output. open("out. txt"); output << "Hello world"; output << "goodbye" << endl; output. put('A'); output. close(); File out. txt: Hello worldgoodbye A
- Slides: 18