int i1;
std::istringstream z(argv[1]);
z >> i1;
cout << i1;
z.str(argv[2]);
int i2;
z >> i2;
cout << i2;
This my code. My first argument is 123 and my second argument is 12. I expect the output to be 12312. Instead I see 1234196880. Why is that? I thought with the str method I could reset the stream to the second argument and read it in ?
When you do
z.str(argv[2]);
the function internally calls the str
member of its internal string buffer object (http://www.cplusplus.com/reference/sstream/stringbuf/str/) and just sets the contents of the string buffer. You need to rewind the pointer in order to use the newly set buffer (http://en.cppreference.com/w/cpp/io/basic_istream/seekg)
I'll assume you're only using istringstream
in order to easily convert strings to integers.
If so, I'd recommend writing a helper function:
template<typename TargetType>
TargetType convert(const std::string& value) {
TargetType converted;
std::istringstream stream(value);
stream >> converted;
return converted;
}
That way, your code becomes more readable, and you avoid having to reset the stream for each conversion:
int i1 = convert<int>(argv[1]);
int i2 = convert<int>(argv[2]);
Edit: If your compiler supports C++ 11, you could also simply use std::stoi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With