C ++排除非整数用户输入

时间:2015-04-02 10:53:35

标签: c++ arrays

我正在制作一个数字猜谜游戏,要求用户输入一个四位数字。然而,有可能用户输入少于或多于四位的数字和/或非整数输入(即无效输入)。我的代码将用户输入存储到整数类型数组中。我刚刚意识到我的代码仍然会识别"无效输入"因为存储输入的数组被声明为整数类型,所以它是有效的。以下是我的代码的一部分:

#include <iostream>
using namespace std;

void guess(int num_guess[], int size);

int main(){
        int list[4];
        guess(list, 4);
        for(int i = 0; i < 4; i++){
            cout << list[i];
        }
        cout << endl;
}
void guess(int num_guess[], int size){
    int number;
    cin >> number;
    for(int i = size-1; i >= 0; i--){
        num_guess[i] = number%10;
        number /= 10;
    }
}

cout << list[i];并不是原始代码的真正组成部分,但这就是我发现无效输入仍然被接受的方式。在我使用Python制作合理的根计算器程序之前,我遇到了类似的问题,但是检测和排除不需要的输入要容易得多。我的问题是,我如何修复我的代码,以便它可以检测无效输入并输出类似&#34;无效输入&#34;然后继续询问用户另一个输入。

5 个答案:

答案 0 :(得分:3)

以下是检查string是否为4位正整数的函数。如果数字可能是负数,您只需要检查s[0] == '-'

bool check(string &s){
    if(s.size() != 4) return false;
    for(int i=0; i < 4; i++){
        if(s[i] < '0' || s[i] > '9') return false;
    }
    return true;
}

以下是将string转换为int的功能:

#include <stringstream>
int strToInt(string &s){
    stringstream ss(s);
    int ans;
    ss >> ans;
    return ans;
}

答案 1 :(得分:1)

要排除非整数输入,请尝试以下操作:

void skip_to_int(){
// if is not an integer
if(cin.fail()){
   // check character type
   cin.clear();
   char ch;
   while(cin>>ch){
      // throw away non digits
      if(isdigit(ch)){
          // put back if digit to be written
          cin.unget();
          return;}
   }

}
else error ("no input");
}

您的输入提示功能如下所示:

cout << "Please enter an integer" << endl;
int n=0;
if(cin>>n){
// integer OK, proceed
}
else{
    cout << "That was not a numeric value, try again." << endl;
    skip_to_int();}

答案 2 :(得分:1)

这是我的解决方案。当心,它使用C ++ 11。如果你使用std::stringstream,当然没有必要,但这应该可以很好地工作。

我认为你不想要负数。我还假设前面的任何数字都不会使数字成为4位数字。它将切断填充0,因此01234是4位数字,但0123不是。

void guess(int num_guess[], int size) 
{
    int number;

    // if the length of the number isn't 4, try again until it is
    do { 
       std::cin >> number; 
       if(std::to_string(number).length() != size) 
          std::cout << "You messed up the input. How hard could it be? Try again..." << std::endl;
    } while(std::to_string(number).length() != size);

    // by now, the size is definitely 4. insert it by digit into num_guess
    for(int i = size-1; i >= 0; i++) {
      num_guess[i] = number%10;
      number /= 10;
    }
}

答案 3 :(得分:0)

添加 #include&#34; math.h&#34;

并更改猜测

void guess(int num_guess[], int size){
  int number = 0;
  bool firstTime = true;
  do 
  {
    if (!firstTime)
      cout << " Error, try again " << endl;
    firstTime = false;
    cin >> number;
  } while (number<pow(10, size-1) || number>=pow(10, size));
  for(int i = size-1; i >= 0; i--){
      num_guess[i] = number%10;
      number /= 10;
  }
}

答案 4 :(得分:0)

#include <iostream>                                                             
#include <limits>                                                               

int main() {                                                                    
    int i = 0;                                                                  

    std::cout << "Please enter a number with four digits: ";                    
    while( !(std::cin >> i) || !(i / 1000.0f >= 1.0f) )                          
    {                                                                           
        std::cin.clear();                                                       
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');     
        std::cout << "Invalid entry." << std::endl;                             
        std::cout << "Please enter a number with four digits: ";                
    }                                                                           
}

std :: cin.clear()清除当前流结构上的所有错误标志,std :: cin.ignore()清除输入流本身。一旦我们不知道流的大小,直到这个操作我已经使用了流大小的最大可能值来确保可以清除任何流长度。

相关问题