Difference between revisions of "CPP/StringStream"
From ProgrammingExamples
< CPP
Daviddoria (Talk | contribs) (Created page with '==StringStream.cpp== <source lang="cpp"> #include <iostream> #include <string> #include <sstream> void StringToNumber(); void TestClear(); void NumberToString(); int main(int a…') |
Daviddoria (Talk | contribs) m |
||
Line 41: | Line 41: | ||
void TestClear() | void TestClear() | ||
{ | { | ||
+ | // Create a stringstream and add "hello1" to it | ||
std::stringstream TestStream1; | std::stringstream TestStream1; | ||
TestStream1 << "hello" << 1 << std::endl; | TestStream1 << "hello" << 1 << std::endl; | ||
std::cout << TestStream1.str(); | std::cout << TestStream1.str(); | ||
+ | // Clear the stringstream, and then add "hello2" to it and show that "hello2" is now the only thing in the stream | ||
TestStream1.str(""); | TestStream1.str(""); | ||
TestStream1 << "hello" << 2 << std::endl; | TestStream1 << "hello" << 2 << std::endl; | ||
std::cout << TestStream1.str(); | std::cout << TestStream1.str(); | ||
+ | // Also just setting str() to something else clears the stream implicitly | ||
TestStream1.str("hello3"); | TestStream1.str("hello3"); | ||
std::cout << TestStream1.str(); | std::cout << TestStream1.str(); |
Latest revision as of 20:20, 7 August 2011
StringStream.cpp
#include <iostream> #include <string> #include <sstream> void StringToNumber(); void TestClear(); void NumberToString(); int main(int argc, char *argv[]) { //TestClear(); NumberToString(); return 0; } void Test() { /* StringToNumber(); std::stringstream TestStream1; TestStream1 << "hello" << 1 << std::endl; std::cout << TestStream1.str(); //TestStream1.clear(); //TestStream1.str().erase(); TestStream1.str(""); TestStream1 << "hello" << 2 << std::endl; std::cout << TestStream1.str(); std::stringstream TestStream2("hello"); std::cout << TestStream2.str(); TestStream2 << "world"; std::cout << TestStream2.str(); */ } void TestClear() { // Create a stringstream and add "hello1" to it std::stringstream TestStream1; TestStream1 << "hello" << 1 << std::endl; std::cout << TestStream1.str(); // Clear the stringstream, and then add "hello2" to it and show that "hello2" is now the only thing in the stream TestStream1.str(""); TestStream1 << "hello" << 2 << std::endl; std::cout << TestStream1.str(); // Also just setting str() to something else clears the stream implicitly TestStream1.str("hello3"); std::cout << TestStream1.str(); } void StringToNumber() { std::string strNumber = "23.4"; std::cout << "strNumber = " << strNumber << std::endl; std::stringstream ss; ss << strNumber; double dNumber; ss >> dNumber; std::cout << "dNumber = " << dNumber << std::endl; } void NumberToString() { int intNumber = 13; //put the number in a stringstream std::stringstream ss; ss << intNumber; //get the number out of the stringstream as a string std::string strNumber; ss >> strNumber; std::cout << "strNumber = " << strNumber << std::endl; }