c++ - 将 int 添加到 vector 中

标签 c++ vector while-loop cin

我刚刚开始学习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/

相关文章:

c++如何声明返回对象 vector 的函数

c++ - 在 vector C++ 中查找对象的指针

java - 循环检查密码

bash - While 循环在 Bash 中的第一行之后停止读取

在 while 循环中使用 continue 后代码未执行

c++ - 函数错误 "was not declared in this scope"

c++ - 为什么枚举不能是模板?

c++ - 为什么我不能链接到boost的线程库?

c++ - 检测到堆损坏

c++ - 使用 swap-and-pop 迭代时删除 vector 中的元素