0

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

我正在尝试读取一些数字并将它们写入 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”时(在这个例子中,除了数字之外的所有内容)循环停止,我想问用户应该添加多少个数字。显示 cout 命令,但正在跳过输入。所以我的程序没有从我想添加的向量中读取多少值。

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

祝你今天过得愉快 :)

4

2 回答 2

0

因为您的输入变量是类型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'); 

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

于 2013-11-06T08:45:37.057 回答
0

第一个答案已经解释了如何在用户输入字符后刷新 cin 流。如果要确定它是哪个字符,则应定义userInputstd::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

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

于 2013-11-06T09:27:42.003 回答