【发布时间】:2020-12-19 04:29:31
【问题描述】:
我首先读取一些 int 数并将其存储在一个名为 my 的向量中,然后我尝试先对 size 数求和。这是我完成的代码:
vector<int>my;
cout << "please enter num:" << endl;
int item;
while(cin>>item){
my.push_back(item);
}
cout << endl;
for(auto i:my){
cout << i << " ";
}
cout << "\nplease enter the num you want to sum: " << endl;
int size;
cin >> size;
vector<int>myvector;
for(int i=0;i<size;++i){
myvector.push_back(my[i]);
}
cout << "\nthe nums are: ";
int total{0};
for(auto t:myvector){
cout << t << " ";
total += t;
}
cout << "\nthe total is: " << total << endl;
结果:
please enter num:
3
1
2
3
4
5
]
3 1 2 3 4 5
please enter the num you want to sum:
the nums are:
the total is: 0
如您所见,从第二个提示开始,代码无法正常工作,没有给我预期的结果,所以我只是将第二个提示移到顶部,然后它就可以工作了;
cout << "\nplease enter the num you want to sum: " << endl;
int size;
cin >> size;
vector<int>my;
cout << "please enter num:" << endl;
int item;
while(cin>>item){
my.push_back(item);
}
cout << endl;
for(auto i:my){
cout << i << " ";
}
vector<int>myvector;
for(int i=0;i<size;++i){
myvector.push_back(my[i]);
}
cout << "\nthe nums are: ";
int total{0};
for(auto t:myvector){
cout << t << " ";
total += t;
}
cout << "\nthe total is: " << total << endl;
please enter the num you want to sum:
3
please enter num:
1
2
3
4
5
]
1 2 3 4 5
the nums are: 1 2 3
the total is: 6
有什么想法吗?
【问题讨论】:
-
while(cin>>item){将继续从cin读取,直到流关闭。你确定这是你想要的吗? -
@scohe001 看来 OP 正试图通过输入
]来“停止” cin,不幸的是,这也是他们的程序无法运行的原因 -
OT,但
myvector是干什么用的?为什么它必须是与my不同的对象?为什么不能将其初始化为vector<int>myvector = my;?另外,如果size与my中的实际元素数量不同会怎样? -
提供非整数输入将设置流的失败状态。只要流处于失败状态,就不能使用它来读取任何输入。您必须
clear州。 -
知道了。非常感谢你们,很酷。
标签: c++