具有向量成员的结构的istream

istream for a struct with a vector member

本文关键字:结构 istream 成员 向量      更新时间:2023-10-16

我不太清楚istream是如何从标准输入(例如键盘上的cin>>)工作的对于具有向量成员的结构。我有一个简单的结构,包含double、string和vector成员。我想阅读cin的结构,并用cout打印它们。我使<lt;和>>操作员,这是我的代码:

    #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停止输入如果我在主cin>>test1;cout<<test1;中有,我可以读取和打印单个结构我一直在寻找一个合适的解决方案,但我没能找到。

非常感谢您的帮助。

snek

添加一个"点击键继续"并将test1变量放入循环中应防止"矢量混淆"

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