snek
snek

Reputation: 81

istream for a struct with a vector member

Its not very clear to me how istream works from standard input (i.g. cin>> from keyboard) for a structure that has a vector member. I have a simple struct with double, string and vector members. I want to read structs from cin, and printing them with cout. I overload the << and >> operators and here is my code:

    #include <iostream>
#include <vector>
#include <string>
using namespace std;


struct Test {
    double d;
    string s;
    vector<int>vi;
    Test():d(0.0),s(string()),vi(0)     
    {}
    Test(double d1,string s1,vector<int>vi1):d(d1),s(s1),vi(vi1)    
    {}
};

istream &operator>>(istream &is, vector<int>&v)
{
    int x;
    cout<<"type the vector<int>elements :"<<endl;
    while (is>>x)
        v.push_back(x);
    is.clear();
    return is;
}

ostream &operator<<(ostream &os, vector<int>&v)
{
    os<<"[ ";
    for (int i=0;i<v.size();i++)
        os<<v[i]<<" ";
    os<<" ]";
    return os;
}

istream &operator>>(istream &is, Test &t)
{
    cout<<"type the double d value: ";
    is>>t.d;
    cout<<"type the string s value: ";
    is.ignore();                    //call ignore before getline
    getline(is,t.s);
    //int x;
    //cout<<"type the vector elements:"<<endl;  //try to use the vector<int> istream operator
    //while (true) {
    //  if (is.eof()==1) break;
    //  t.vi.push_back(x);
    //}
    //is.clear();
    is>>t.vi;
    is.clear();
    return is;
} 


ostream &operator<<(ostream &os, Test &t) 
{
    os<<"{ ";
    os<<t.d<<" , "<<t.s<<" , ";
    os<<t.vi;
    os<<" }"<<endl;
    return os;
}

int main()
{
    Test test1;
    while (cin>>test1)
        cout<<test1;


}

I have in main the while (cin>>test1) cout<<test1 to read and print the structs. But as soon a read a second struct from cin I get the following:

./testin
type the double d value: 1.0
type the string s value: 1st struct string
type the vector<int>elements :
1
1
1
{ 1 , 1st struct string , [ 1 1 1  ] }
type the double d value: 2.0
type the string s value: 2nd struct string
type the vector<int>elements :
2
2
2
{ 2 , 2nd struct string , [ 1 1 1 2 2 2  ] }
type the double d value:

The vector is mixed up, plus that I cannot stop the input with CTRL+d I m able to read and print a single struct , If I have in main cin>>test1;cout<<test1; I looked for a proper solution a lot , but I did not manage to figure it out.

Thanks a lot for any help in advanced.

snek

Upvotes: 2

Views: 1545

Answers (1)

alexbuisson
alexbuisson

Reputation: 8469

add a "hit key to continue" and put the test1 var inside the loop should prevent the "vector-mix up"

    do  {
     Test test1;
    cin >> test1;
    cout << test1;
    } while (getchar() == 'c')

Upvotes: 1

Related Questions