具有向量成员的结构的istream
istream for a struct with a vector member
我不太清楚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')
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 为什么istream不支持右值提取
- 如何重构类层次结构以避免菱形问题
- 将无符号char*转换为std::istream*C++
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 逗号在重载 ostream 和 istream 在结构中分开
- 具有向量成员的结构的istream
- 对使用带istream形参的结构体感到困惑