string s = "hello"; // implicit conversion Not just an array of chars ending in \0"> string s = "hello"; // implicit conversion Not just an array of chars ending in \0">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Strings References: www.cplusplus.com/reference/fstream/basic_ifstream :" iomanip, sstream.

Similar presentations


Presentation on theme: "C++ Strings References: www.cplusplus.com/reference/fstream/basic_ifstream :" iomanip, sstream."— Presentation transcript:

1 C++ Strings References: :" iomanip, sstream

2 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 Not just an array of chars ending in \0

3 String Indexing string s = "hi ya!";
Two ways to access characters in string: char c1 = s[3]; // 'y' char c2 = s.at(1); // 'i' Recall that characters have ASCII encodings: cout << (int) 'B' << endl; // 66 index 1 2 3 4 5 character 'h' 'i' ' ' 'y' 'a' '!'

4 String Operations Concatenate strings with +:
string s = "Hello"; string s1 = s + " World"; // "Hello World" Compare strings with relational operators: string s2 = "Hi"; if(s1 < s2 && s2 != "Bye") { // true ... } Add and change characters in strings: string s1 = "Mary"; s1.append(" Eberlein"); // "Mary Eberlein" s1.erase(1, 3); // "M Eberlein" s1[1] = 'e'; // "MeEberlein" C++ strings can be modified. Add to end (append),

5 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!"

6 String Comparison string str1 = ... ; string str2 = ... ;
if(str1 == str2) // compares characters if(str1 < str2) // compares in dictionary order

7 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 If you've learned Java, these are similar of available String methods. string::npos a weird error constant! string greeting = "hello world"; if(greeting.find("hello") != string::npos) { greeting.erase(0, 6); // "world" }

8 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; Note in mystery: b reference parm. mystery: a is "ary" b is "eberleina" b is "ebeFOOrleina" main: After call: a = "mary", b = "ebeFOOrleina" Answer output: mary ebeFOOrleina a is passed by value, so in main, it's still mary. In eberlein, at index 3, FOO gets inserted.

9 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 Look at C++.com and Cpp.com to look up function descriptions Include links to relevant libraries for schedule entry C++ has better more powerful strings. But C++ is backwards compatible with C, so have the old C type string also. Ex: string s = "hello"; // the C style string is automatically converted to a C++ string when I assign it to string s. So I can call functions on it. Behavior of 2 types of strings is different. Careful. C string – not much functionality, just stores the characters in a block of memory C++ string: object with member functions C strings cannot be concatenated with + Also ok: string("hello") + " world"  As long as one is a C++ string, operations ok. Type promotion

10 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; stream << s << " " << 41; s = stream.str(); cout << s; // prints: hi 41 Or use sprintf

11 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 cout << "Enter your name, please: "; getline(cin, name); cout << "Hello, " << name << endl; Output: Hello, Anna Banana Note: getline – 2nd parm is a reference parm

12 I/O Streams Standard and FiLE I/O

13 I/O Streams COMMAND HOW IT WORKS cout << expression
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

14 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; cout << setbase(16); cout << 100 << endl; Output is hexadecimal value of 100, i.e., 64 cout << setfill('x') << setw(10) << 55; Output: xxxxxxx55

15 File I/O cin – variable of type ifstream
#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("goodStuff.txt"); // Open the file string line; while(getline(input, line)) { // Read every line cout << line << endl; } input.close(); // close file stream is a source or destination of data ifstream – input file stream ofstream – output file stream getline function: takes 2 parms: ifstream and reference to a string in which to store what's read Function getline returns boolean: true if read was successful, false otherwise (including when end of file reached)

16 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() 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 Was your last read a failure or not (f.fail) Arrow syntax used with cin works also. ifstream input; input.open("numbers.txt"); int n; input >> n; Can cause issues if reading lines and tokens both Also: what if input is not numeric/integer? Solution: Read with getline. Use string conversion functions: strtof, strtol, strtod (string to double), ... include cstdlib: #include<cstdlib> OR:Read the number. Check to see if input stream is still valid. If input stream is not (!cin), call cin.clear() to take stream out of fail state. Remove the input that caused the problem (cin.ignore()), get input again if appropriate

17 Example What does this do? while(!input.fail()) {
getline(input, line); cout << line << endl; } Prints the last line twice. input.fail() tells you if the last time you read failed or not. This goes one time too many, and prints last line twice. while I didn't fail the last time I read a line { ... }  Not correct Instead, use: while(getline(input, line)) { cout << line << endl; }

18 ofstream functions function description stream << expression
writes expression to output stream stream.put(ch) Writes character 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


Download ppt "C++ Strings References: www.cplusplus.com/reference/fstream/basic_ifstream :" iomanip, sstream."

Similar presentations


Ads by Google