【问题标题】:Adding int into a vector将 int 添加到向量中
【发布时间】: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 &gt;&gt; 将在失败时返回 false。这是预期的行为。如果要处理无效输入,则需要自己处理。
  • @Yksisarvinen 不,不会的。它只会返回对流的引用。但是当设置了错误标志时,这会评估为假

标签: c++ vector while-loop cin


【解决方案1】:

std::cin&gt;&gt;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 &gt;&gt; n; 行上再次准备就绪。

【讨论】:

  • std::cin.ignore(INT_MAX); ~> std::cin.ignore(std::numeric_limits<:streamsize>::max(), '\n');
  • 这是假设换行符分隔非数字输入
  • @Caleth 你是对的。是否有一个通用的解决方案无论如何都会清除缓冲区?
  • 谢谢,它可以工作 :) 虽然我不明白 (std::numeric_limits<:streamsize>::max(), '\n') 并且即使我删除它它也会继续工作
  • @Blaze 字符串的最大大小~>流的最大大小
猜你喜欢
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 2012-04-27
  • 2012-03-16
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
相关资源
最近更新 更多