Overriding >> operator of stringstream for conversion

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 :-)
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] ?
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
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.
@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.