I recently started playing around with stringstream. From my understanding (which could be wrong) it acts like a string container but with some extra functions associate with the container.
Below is some code that converts a
char
to an
int
I know it works, my question is why it works.
This is what I think is happening.
*The program creates a stringstream container called str.
*a value of '1' gets put into the container with str << '1';
*The program then creates an integer variable called x.
*Then some how (as if by magic) the stringstream converts the char to an integer. |
My problem is I don't understand how stringstream does it's magic.
I've found other ways that I understand how they work, like
x = '1' - '0'
but from what I've read people say it's C style implementation instead of C++ and I'd like to understand the C++ way.
Does anybody have any reference on how stringstream converts values to different data types. I read the stringstream article on this site but it didn't really explain what sort of limitations stringstream has on data type conversions (if there are any) and
http://www.cplusplus.com/reference/sstream/stringstream/
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
Does the stringstream operator
>>
basically perform the C style
x = '1' - '0'
automatically when you use the operator?
I think i sort of worked my way through understanding this by writing it out but if anybody could verify the picture I have in my head of how this works is correct I'd be grateful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream str;
str << '1';
int x;
str >> x;
std::cout << "x + 1 is equal to : " << x + 1 << "\n";
return 0;
}
|
Also, this I can't seem to reuse the same variable with a stringstream.
Line 19 below comes out to 3 instead of 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream str;
str << '1';
int x;
str >> x;
std::cout << "x + 1 is equal to : " << x + 1 << "\n";
str << '2';
str >> x;
std::cout << "x + 2 is equal to : " << x + 2 << "\n"; //output comes out to 3 instead of 4.
return 0;
}
|