150 likes | 225 Views
Principles of Computer Science I Honors Section. Note Set 10 CSE 1341. Today. String Streams. What’s the difference between:. 255 and “255” ??????????. Background. Web Cam pictures. Rover Communcations. VAB. Mission Control ( YOU ). Background.
E N D
Principles of Computer Science IHonors Section Note Set 10 CSE 1341
Today String Streams
What’s the difference between: 255 and “255” ??????????
Background Web Cam pictures Rover Communcations VAB Mission Control (YOU)
Background • Communication in character strings • s 1 255 • Sent to the robot as a string of characters • Problem: • You have to build the string of characters before you can send it to the robot • You have to interpret the string of characters from the VAB worksheet before you can use them in calculations
Numbers to Strings • Difficult/annoying with c-strings (null terminated char arrays) • Difficult to append a number to a c-string or stl-string //Can’t Do this string s; s = 32; cout << s; //WILL NOT display 32a //Can’t Do this either char str[25]; strcpy(str, 32); //WILL NOT COMPILE cout << s;
c-way or old way • atoi(const char*), atof(const char*)......... • will convert an ascii string of digits to an integer • have to worry about c-string being properly formatted • What if result is too big to fit in an integer??
Remember cout??? • You can send any fundamental data type to cout //This is OK! cout << 32; cout << “32”; cout << “go forward”; cout << 3.456; Can we do something similar, but store the data in a string instead of sending it to the screen?
String Stream • string stream objects handle (behind the scenes) conversion of data types • Can insert or extract information from a string stream using >> and << • Stored in a String behind the scenes stringstream ss; istringstream iss; ostringstream oss;
Example #include <sstream> #include <iostream> int main() { stringstream s; int x = 25; double y = 2.34; s << x; s << “ “; s << y; string str; s >> str; //like cin, but source is s cout << str; //What will this print??? return 0; }
Example stringstream ss; ss << “1 2 3 4 5 6”; int temp; for (int i = 0; i < 6; i++) { ss >> temp; cout << temp * 2; } 2 4 6 8 10 12
Example stringstream ss; char str[] = “1 2 3 4 5 6”; ss << str; int temp; for (int i = 0; i < 6; i++) { ss >> temp; cout << temp * 2; } 2 4 6 8 10 12
Functions • str() • return a stl-string copy of what’s in the stringstream • getline(…) • used as if you were getting a line from cin
Example stringstream ss; string temp; ss << "C++ is the best ever!"; ss >> temp; cout << temp; cout << endl; getline(ss, temp); cout << temp; C++ is the best ever!