我刚刚开始学习c++,我遇到了这个小问题。我尝试将输入的整数放入 vector 中,并在不再输入整数时停止。
为此我使用
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>>x
因为遇到字符而失败时,该字符不会被删除。因此,当您稍后尝试获取另一个整数时,它将因同样的原因而失败。您可以通过使用 std::cin.ignore
刷新缓冲区并使用 std::cin.clear
重置错误标志来清理 Steam 。此行之后:
while(std::cin>>x) v.push_back(x);
添加此:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
这样,流就为空,并在您尝试读取另一个整数的 std::cin >> n;
行上再次准备就绪。
关于c++ - 将 int 添加到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235252/