gpt4 book ai didi

c - 如何在 C 中仅读取输入中的数字(没有字母,只有数字)?

转载 作者:行者123 更新时间:2023-11-30 18:58:56 24 4
gpt4 key购买 nike

你不久前帮我读了一行字。现在,我只想读取输入中的数字 - 没有字母,只有 5 位数字。我怎样才能做到这一点?

我的解决方案无法正常工作:

int i = 0; 
while(!go)
{
printf("Give 5 digits: \n\n");
while( ( c = getchar()) != EOF && c != '\n' && i < 5 )
{
int digit = c - '0';
if(digit >= 0 && digit <= 9)
{
input[i++] = digit;
if(i == 5)
{
break;
go = true;
}
}
}
}

最佳答案

使用 break 语句,go = true; 将永远不会被执行。因此循环 while (!go) 是无限的。

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

int i = 0;
int input[5];

printf ("Give five digits: ");
fflush (stdout);

do
{
c = getchar ();

if (isdigit (c))
{
input[i] = c - '0';
i = i + 1;
}
} while (i < 5);

关于c - 如何在 C 中仅读取输入中的数字(没有字母,只有数字)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482852/

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