使用带c,c ++的do-while循环检查输入

时间:2010-11-10 06:09:44

标签: c++ visual-c++

您好我正在尝试使用do-while循环检查输入并重复提示,直到用户键入正确的整数。这就是我的代码:

#include <iostream>
#include <stdio.h>
#include <ctype.h>    

int main ()
{

  int a;

  do
  {
     printf("Please type in your number: ");
  }while(scanf_s("%d", &a) == 0); 

  std::cin.get();
  std::cin.get();

  return 0;
}
好吧它好像有效。当我输入一个数字时,程序运行正常。但是当我输入一个字母时,无限循环开始。我真的不知道问题出在哪里。

7 个答案:

答案 0 :(得分:4)

同样,我建议在一个字符串中读取一行,然后根据您的需要尝试解析该字符串。如果解析失败,只需再次提示用户。您可以将杂乱的细节隐藏在功能模板中:

#include <iostream>
#include <sstream>
#include <string>

template <typename T>
T read(std::string prompt)
{
    for (; ;)
    {
        std::cout << prompt;
        std::string line;
        getline(std::cin, line);
        std::istringstream ss(line);
        T x;
        if ((ss >> x) && (ss >> std::ws).eof()) return x;
    }
}

int main ()
{
    int a = read<int>("Please type in your number: ");
    std::cout << "You entered " << a << '\n';
}

答案 1 :(得分:3)

这是发生了什么 - 我将逐步完成。从do开始:

  1. 输出:请输入您的电话号码:
  2. 致电scanf Scanf发现stdin为空,因此等待输入一行。
  3. 输入:letter(请注意,输入缓冲区现在包含“letter”)
  4. scanf尝试将字符串解析为整数。解析在消耗任何字符之前失败。因此缓冲区仍然包含“字母”
  5. scanf返回EOF(错误)
  6. 输出:请输入您的电话号码:
  7. 致电scanf - scanf看到stdin
  8. 中已有等待输入
  9. scanf尝试将缓冲区解析为整数.....
  10. 这将永远持续下去,因为scanf永远不会消耗缓冲区中的字符。您可以通过正确检查scanf的错误返回码来解决问题。

答案 2 :(得分:0)

首先,永远不要使用scanf作为一个危险功能的地狱。

如果您想坚持使用C,您应该使用fgets将用户的输入读取到缓冲区,然后atoi将用户的输入转换为整数。

注意:fgets总是将'enter'添加到缓冲区中,因此您希望在转换缓冲区内容之前将其删除。

这可以很容易地完成如下:

_buffer[strlen(_buffer)-1] = '\0';

答案 3 :(得分:0)

我修改了我的代码,以便它现在可以正常工作。但是,它真的只适用于数字和字母。我希望它可以与每个字符一起使用。例如 ”!?%”。我已经尝试通过“isascii”更改“isalnum”但这不起作用。

#include <stdio.h>
#include <ctype.h>

int main ()
  {

    int a;
    int b = 1;
    char c ;

    do
    { 
      printf("Please type in a number: ");

      if (scanf("%d", &a) == 0)
      {
        printf("Your input is not correct\n");
        do 
        {
          c = getchar();
        }
        while (isalnum(c));  
        ungetc(c, stdin);    
      }
      else
      { 
      printf("Thank you! ");
      b--;
      }

    }
    while(b != 0); 

    getchar();
    getchar();

    return 0;
  }

答案 4 :(得分:0)

@ ordo

  

Blockquote

我修改了我的代码,以便它现在可以正常工作。但是,它真的只适用于数字和字母。我希望它可以与每个字符一起使用。例如 ”!?%”。我已经尝试通过“isascii”更改“isalnum”但这不起作用。

  

块引用

您可以使用

if(userInput&gt; ='!'&amp;&amp; userInput&lt; ='〜')//请参阅!和〜之间的ASCII图表。     {exit = 0; }

http://www.cdrummond.qc.ca/cegep/informat/professeurs/alain/images/ASCII1.GIF

答案 5 :(得分:-1)

int main ()
{    
  int a;
  char userInput,exit=1;

  do
  {
     printf("Please type in your number: ");
     userInput=getch();

     if(userInput=='1') // suppose the correct input is 1.
     { exit=0; }         

  }while(exit); 

  std::cin.get();
  std::cin.get();

  return 0;
}

如果输入介于09 ...

之间
 if(userInput>='0'&& userInput<= '9') // suppose the correct input is 1.
    { exit=0; }

请注意,我们必须使用''标志

答案 6 :(得分:-2)

您可以使用getchar()功能

do
  {
     printf("Please type in your number: ");
  }while((getchar() - '0') == 0);