I want to use a string stream to convert an int to a string, then a string to an int use the same stringstream. If I declare two like this, it works fine:
Code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
const int iNum = 56;
std::string sNum;
const std::string str("78");
int num;
std::stringstream ss;
//stuff int into the stream
ss<<iNum;
//release the stream as an string
sNum = ss.str();
//print both results
std::cout<<"iNum: "<<iNum<<std::endl;
std::cout<<"sNum: "<<sNum<<std::endl;
std::stringstream ss1;
ss1<<str;
ss1>>num;
std::cout<<"str: "<<str<<std::endl;
std::cout<<"num: "<<num<<std::endl;
std::cin.ignore();
std::cin.get();
}
Here is the output:
Code:
iNum: 56
sNum: 56
str: 78
num: 78
This is exactly what I expect. But what if when I am writing the program I don't want to have to declare multiple string streams? Basically this is what I want to do:
1. declare a string stream object
2. stuff an integer in it
3. call the str() function on the object to get the int value as a string
4. *here is the confusing part. Now i need to clear this stream. I don't know how without declaring a new string stream object*
5. Then I want to stuff a string into the cleared string stream object
6. Now I want to put the stream into an int and print the value.
Below is my attempt at this:
Code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
const int iNum = 56;
std::string sNum;
const std::string str("78");
int num;
std::stringstream ss;
//stuff int into the stream
ss<<iNum;
//releaase the stream as an string
sNum = ss.str();
//print both results
std::cout<<"iNum: "<<iNum<<std::endl;
std::cout<<"sNum: "<<sNum<<std::endl;
/**********Need to somehow clear the stream here*****/
ss<<str;
ss>>num;
std::cout<<"str: "<<str<<std::endl;
std::cout<<"num: "<<num<<std::endl;
std::cin.ignore();
std::cin.get();
}
Here is my output:
Code:
iNum: 56
sNum: 56
str: 78
num: 5678
Obviously my stream isn't getting cleared. Inthe above point where I need to clear the stream I have tried everything on this page that looks applicable: http://www.cppreference.com/cppio/index.html
Code:
1. ss.clear();
2. ss.flush();
3. ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I just don't know what to put there. Any ideas? Thanks.