Overriding >> operator of stringstream for conversion
Apr 6, 2012 at 7:13pm UTC
Hello :-),
Well,
1 2 3 4 5 6
stringstream str;
str << 10;
double x;
str >> x;
This code is supposed to convert what's in str to double.
What if the type is not a native type? like a vector, for example. Then I'll have to overload the >> operator.
Here's my code, but it doesn't work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
void operator >> (std::stringstream &out, v3 &t)
{
cout<<out<<endl; //this shows the address and not the value... god knows why!!!
double i;
std::vector<double > vect;
while (svalue >> i)
{
vect.push_back(i);
if (svalue.peek() == ',' )
svalue.ignore();
}
if (vect.size() != 3)
{
throw std::length_error("Invalid_v3_length" );
}
else
{
t[0] = vect[0];
t[1] = vect[1];
t[2] = vect[2];
}
}
v3 is a simple 3 components vector (math vector).
Any help is highly appreciated :-)
Apr 6, 2012 at 7:36pm UTC
How do you break the while loop ?
and sorry i am not able to understand why are you using the three vector as ...vect[0] , vect[1] , vect[2]
?
Apr 6, 2012 at 7:41pm UTC
I think this is what you want:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
class v3
{
public :
// ...
friend istream &operator >>(istream &out, v3 &t)
{
cout<<out<<endl;
double i;
std::vector<double > vect;
while (out >> i)
{
vect.push_back(i);
if (out.peek() == ',' )
out.ignore();
}
if (vect.size() != 3)
{
throw std::length_error("Invalid_v3_length" );
}
else
{
t[0] = vect[0];
t[1] = vect[1];
t[2] = vect[2];
}
return out;
}
};
int main()
{
stringstream ss("10, 20, 30" );
v3 v;
ss >>v;
}
Last edited on Apr 6, 2012 at 7:42pm UTC
Apr 6, 2012 at 7:41pm UTC
What is svalue?
cout<<out<<endl; //this shows the address and not the value... god knows why!!!
I think it should be out.str(), but I rarely use stringstream.
Apr 6, 2012 at 7:46pm UTC
@Null: Thanks a lot. That's it ^^
@naraku9333: it's out, but I had to change it to out.
Thanks a lot again for you efforts :)
Topic archived. No new replies allowed.