将 int 添加到向量中
Adding int into a vector
刚开始学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>>x
因为遇到一个字符而失败时,该字符不会被删除。所以当你稍后尝试获取另一个整数时,它会因为同样的原因而失败。您可以通过使用 std::cin.ignore
刷新缓冲区并使用 std::cin.clear
重置错误标志来清理蒸汽。在这一行之后:
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++,遇到这个小问题。我尝试将与我输入的整数一样多的整数放入向量中,并在我不再输入整数时停止。
为此我使用
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
重置错误标志来清理蒸汽。在这一行之后:
while(std::cin>>x) v.push_back(x);
添加这个:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
这样,流为空,并在您尝试读取另一个整数的 std::cin >> n;
行再次准备就绪。