gpt4 book ai didi

c - 使用 c 检查用户输入的 do-while 循环

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:58 25 4
gpt4 key购买 nike

我正在使用这段代码来读取用户输入并检查它是否是数字。但老实说它只适用于数字和字母。我希望它适用于每个字符。例如 ”!?%”。我已经尝试用“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;
}

最佳答案

除非您有特殊要求,否则您应该使用fgetssscanf

while (1) {
char buf[1000];
printf("Please input a number: ");
fflush(stdout);
if (!fgets(buf, sizeof buf, stdin)) assert(0 && "error in fgets. shouldn't have hapenned ..."):
/* if enter pending, remove all pending input characters */
if (buf[strlen(buf) - 1] != '\n') {
char tmpbuf[1000];
do {
if (!fgets(tmpbuf, sizeof tmpbuf, stdin)) assert(0 && "error in fgets. shouldn't have hapenned ...");
} while (buf[strlen(tmpbuf) - 1] != '\n');
}
if (sscanf(buf, "%d", &a) == 1) break; /* for sufficiently limited definition of "numbers" */
printf("That was not a number. Try again\n");
}

关于c - 使用 c 检查用户输入的 do-while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4172370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com