【问题标题】:stop inupt if input no double如果输入没有双精度则停止输入
【发布时间】:2013-11-06 08:35:05
【问题描述】:

首先我很抱歉我的 英语不好。

我正在尝试读取一些数字并将它们写入 C++ 中的向量。 只要输入是双数并且 如果用户写入“a”,则应停止循环。

我的问题是如何检查输入是否为“a”。 打破循环不是问题

while(true){
    if(!(cin>>userInput)){
        //here i want to know if the input is 'a' or some other stuff//
        //also i want to do some other stuff like printing everything//
        //what already is in the vector//
        //when everything is done; break//
       }
    else
       //the input is a valid number and i push it into my vector//

'userInput' 被定义为双精度,因此循环将停止。 我的问题是,如果用户写 'q' 循环停止,但它会立即停止整个程序。我的尝试如下所示:

    while(true){    //read as long as you can
    cout<<"Input a number. With 'q' you can stop: "<<endl;
    if(!(cin>>userInput)){ //here the progam stops when the input is anything but a number
        cout<<"How many numbers do you want to add up?"<<endl; //there are numbers in a vector that should be added up
        cin>>numberOfAdditions;
        break;
    }

所以我有一个向量,其中包含用户写下的一些数字(20、50、90、...) 当输入等于 'q' 时(在本例中,除了 numbers 之外的所有内容) 循环停止,我想问用户应该添加多少数字。 显示 cout 命令,但正在跳过输入。 所以我的程序没有从我想添加的向量中读取多少值。

我希望你明白我的意思,我不想使用两个问题和两个变量来保存输入,但如果没有它就无法工作,我会改变我的程序。

祝你有美好的一天:)

【问题讨论】:

标签: c++ input vector output


【解决方案1】:

因为您的输入变量是double 类型,您必须在再次读取之前从 cin 刷新输入。否则缓冲区中仍有换行符。 考虑以下示例:

#include <iostream>

using namespace std;

int main(){
  double userInput;
  int numberOfAdditions;
  while(true){    //read as long as you can
    cout<<"Input a number. With 'q' you can stop: "<<endl;
    if(!(cin>>userInput)){ //here the progam stops when the input is anything but a number
      cout<<"How many numbers do you want to add up?"<<endl; //there are numbers in a vector that should be added up
      cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
      cin.clear();
      cin.ignore(INT_MAX,'\n'); 
      cin >> numberOfAdditions;
      break;
    }
  }
  return 0;
}

两个语句:

cin.clear();
cin.ignore(INT_MAX,'\n'); 

正在刷新输入流,直到遇到换行符。

【讨论】:

    【解决方案2】:

    第一个答案已经解释了如何在用户输入字符后刷新 cin 流。 如果要确定是哪个字符,应将userInput 定义为std::string。如果字符串不是 "q" 或 "a" 或您要查找的任何内容,则必须将字符串强制转换为双精度,如下所示:

    std::string str;
    cin >> str;
    
    if (str == "j")
        // User typed in a special character
        // ...some code...
    else
        double d = atof(str.c_str());  // Cast user input to double
    

    请注意,如果用户键入的字符串不是您特别查找的字符串,则转换结果为零。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2019-05-18
      • 2021-09-28
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多