简体   繁体   English

使用C,C ++使用do-while循环检查输入

[英]checking input using a do-while loop with c, c++

Hello i'm trying to use a do-while loop to check the input and repeat the prompt until the user types in a correct integer. 您好,我正在尝试使用do-while循环来检查输入并重复提示,直到用户键入正确的整数为止。 So that's my code: 这就是我的代码:

#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;
}

Well it seems to work. 好吧,似乎可行。 When I type in a number the program runs correctly. 当我输入数字时,程序将正确运行。 But when I type in a letter an infinite loop starts. 但是当我输入字母时,无限循环开始。 Sincerly I don't know where the problem is. 真诚的我不知道问题出在哪里。

Again, I suggest reading a line into a string and then trying to parse that string according to your needs. 同样,我建议将一行读入字符串,然后尝试根据您的需要解析该字符串。 If the parse fails, simply prompt the user again. 如果解析失败,只需再次提示用户。 You can bury the messy details in a function template: 您可以将杂乱的细节埋在函数模板中:

#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';
}

Here's what's going on -- I'll go through step by step. 这是正在发生的事情-我将逐步进行。 Starting from the do : do开始:

  1. output: Please type in your number: 输出:请输入您的电话号码:
  2. call to scanf Scanf finds that stdin is empty, and therefore waits for a line to be typed in. 调用scanf Scanf发现stdin为空,因此等待输入一行。
  3. input : letter (note that the input buffer now contains "letter") 输入: letter (请注意,输入缓冲区现在包含“字母”)
  4. scanf attempts to parse the string as an integer. scanf尝试将字符串解析为整数。 Parsing fails before it consumes any characters. 解析在消耗任何字符之前会失败。 Therefore the buffer still contains "letter" 因此,缓冲区仍包含“字母”
  5. scanf returns EOF (error) scanf返回EOF(错误)
  6. output: Please type in your number: 输出:请输入您的电话号码:
  7. call to scanf -- scanf sees that there's already waiting input in stdin 调用scanf - scanf看到stdin已经有等待输入
  8. scanf attempts to parse the buffer as an integer..... scanf尝试将缓冲区解析为整数.....

This will go on forever because scanf will never consume the characters from the buffer. 这将永远持续下去,因为scanf将永远不会占用缓冲区中的字符。 You can solve the problem by correctly checking for an error return code from scanf . 您可以通过正确检查scanf的错误返回码来解决问题。

@ ordo @鄂尔多

Blockquote 大段引用

I have modified my code so that it works now. 我已经修改了代码,以便现在可以使用。 But sincerly it just works for numbers and letters. 但真诚的是,它只适用于数字和字母。 I want it to work with every char. 我希望它与每个字符一起工作。 For example "!?%". 例如 ”!?%”。 I have already tried to change the "isalnum" by "isascii" but that does not work. 我已经尝试过通过“ isascii”更改“ isalnum”,但这不起作用。

Blockquote 大段引用

You can use 您可以使用

if(userInput>='!'&& userInput<= '~') // refer ASCII chart between !and ~. if(userInput> ='!'&& userInput <='〜')//引用!和〜之间的ASCII图表。 { exit=0; {exit = 0; } }

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

First of all never ever use scanf as its one hell of a dangerous function. 首先,永远不要将scanf用作危险功能的地狱。

If you want to stick with C you should use fgets to read the input from the user to a buffer and then atoi to convert the input from the user to an integer. 如果要坚持使用C,则应使用fgets将用户的输入读取到缓冲区,然后使用atoi将用户的输入转换为整数。

Note: fgets always adds the 'enter' in to the buffer so you want to strip it off before converting the content of the buffer. 注意:fgets总是将“ enter”添加到缓冲区中,因此您要在转换缓冲区内容之前先将其剥离。

this could be easily done as follow: 这很容易做到,如下所示:

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

I have modified my code so that it works now. 我已经修改了代码,以便现在可以使用。 But sincerly it just works for numbers and letters. 但真诚的是,它只适用于数字和字母。 I want it to work with every char. 我希望它与每个字符一起工作。 For example "!?%". 例如 ”!?%”。 I have already tried to change the "isalnum" by "isascii" but that does not work. 我已经尝试过通过“ 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;
  }
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;
}

If the input is between 0 and 9 ... 如果输入介于09之间...

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

Note that we have to use ' ' signs 请注意,我们必须使用''符号

You can use getchar() function 您可以使用getchar()函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM