2

对于具有向量成员的结构,我不太清楚 istream 如何从标准输入(来自键盘的 ig cin>>)工作。我有一个带有双精度、字符串和向量成员的简单结构。我想从 cin 读取结构,并用 cout 打印它们。我重载了 << 和 >> 运算符,这是我的代码:

    #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;


}

我主要while (cin>>test1) cout<<test1阅读和打印结构。但是,一旦从 cin 读取第二个结构,我就会得到以下信息:

./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:

向量混淆了,再加上我无法用 CTRL+d 停止输入,我可以读取和打印单个结构,如果我在 main 中cin>>test1;cout<<test1; 寻找了很多合适的解决方案,但我没有设法弄清楚出去。

非常感谢您在高级方面的任何帮助。

斯内克

4

1 回答 1

1

添加一个“点击键继续”并将 test1 var 放在循环中应该防止“向量混合”

    do  {
     Test test1;
    cin >> test1;
    cout << test1;
    } while (getchar() == 'c')
于 2013-07-09T10:31:28.170 回答