gpt4 book ai didi

c - 在 c 中读入一个 int 并忽略其他任何内容

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

我正在尝试使用 scanf() 读取一个 int 以便用于以后的计算,但我试图让它丢弃 int 之后的任何内容。

本质上我希望能够提示用户回答这样的问题

什么是 3 + 5?

并且让用户能够输入 8 或 8 dog 或任何类似性质的内容,并对其进行相同的处理。我试过使用 scanf("%*[^\n]\n"); 但这会导致其他提示,从而导致程序其他地方出现问题无法正确显示。我还应该读入的值(在本例中为 8)用于其他计算,我需要删除狗部分,因为它也会在程序中引起问题。

用于澄清评论中问题的示例代码

printf("What is %d %c %d ", a, oper, b);
fgets(line, sizeof(line), stdin);
errno = 0;
num = strtol(line, NULL, 10);
if (num == answer)
{
printf("Correct!");
right++;
}
else
{
printf("Wrong!");
}
printf("\n");

if (errno != 0)
{
printf("Invalid input, it must be just a number \n");
}

基本上这部分对用户输入的数学问题进行评分

最佳答案

尝试以这种方式读取输入时,使用 scanf 可能会很棘手。我建议使用 fgets 读取整行,然后使用 strtol 将结果转换为数字。

char line[100];
long int num;
fgets(line,sizeof(line),stdin);
errno = 0;
num = strtol(line, NULL, 10);
if (errno != 0) {
printf("%s is not a number!\n", line);
}

编辑:

你所拥有的看起来不错,尽管正如 chux 在评论中指出的那样,它没有正确检测到非数值。

应该这样做:

int main()
{
int a, b, answer, right;;
char oper, *p;
char line[100];
long int num;

right=0;
a=3, b=5, oper='+', answer=8;
printf("What is %d %c %d ", a, oper, b);
fgets(line, sizeof(line), stdin);
errno = 0;
num = strtol(line, &p, 10); // p will point to the first invalid character
if (num == answer)
{
printf("Correct!");
right++;
}
else
{
printf("Wrong!");
}
printf("\n");

if (errno != 0 || p == line)
{
printf("Invalid input, it must be just a number \n");
}
}

关于c - 在 c 中读入一个 int 并忽略其他任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724330/

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