您好我正在尝试使用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;
}
好吧它好像有效。当我输入一个数字时,程序运行正常。但是当我输入一个字母时,无限循环开始。我真的不知道问题出在哪里。
答案 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
开始:
scanf
Scanf发现stdin
为空,因此等待输入一行。letter
(请注意,输入缓冲区现在包含“letter”)scanf
尝试将字符串解析为整数。解析在消耗任何字符之前失败。因此缓冲区仍然包含“字母” scanf
返回EOF(错误)scanf
- scanf
看到stdin
scanf
尝试将缓冲区解析为整数..... 这将永远持续下去,因为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;
}
如果输入介于0
和9
...
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);