【发布时间】:2019-10-07 16:03:13
【问题描述】:
我刚开始学习c++,遇到了这个小问题。我尝试将与输入一样多的整数放入向量中,并在不再输入整数时停止。
为此我使用
while(std::cin>>x) v.push_back(x);
这是我在教科书中学到的,问题是每当我输入任何不是 int 的字符时,即使我的代码后面还有另一个 cin,程序也会停止。
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
int main(){
try{
int x,n;
int sum=0;
std::vector<int> v;
std::cout << "Introduce your numbers" << '\n';
while(std::cin>>x) v.push_back(x);
std::cout << "How many of them you want to add?" << '\n';
std::cin >> n;
if(n>v.size()) throw std::runtime_error("Not enough numbers in
the vector");
for(int i=0; i<n;i++){
sum+=v[i];
}
std::cout<<sum;
return 0;
}
catch(std::exception &exp){
std::cout << "runtime_error" <<exp.what()<< '\n';
return 1;
}
}
【问题讨论】:
-
std::cin >>将在失败时返回false。这是预期的行为。如果要处理无效输入,则需要自己处理。 -
@Yksisarvinen 不,不会的。它只会返回对流的引用。但是当设置了错误标志时,这会评估为假
标签: c++ vector while-loop cin