我正在编写一个代码,要求用户输入10个整数,然后将这些整数反馈给他。我想创建一个" scanf check"限制字符输入。 while循环可以在不接受char的情况下工作,但它会跳过整数输入。
int main()
{
int i = 0, number[10] = {0};
char buf[128] = {0};
for (i = 0; i < 10; i++)
{
printf("Please input number %d : ", i+1);
while(scanf("%d", &number[i]) != 1)
{
scanf("%s", &buf);
printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i);
}
}
for (i = 0; i < 10; i++)
{
printf("\n Number %d is %d", (10-i), number[9-i]);
}
return EXIT_SUCCESS;
}
答案 0 :(得分:4)
正如H2CO3所指出的,不要使用scanf
,另一种选择是fgets
和strtol
:
int i, number[10] = {0};
char buf[128], *p;
for (i = 0; i < 10; i++) {
printf("Please input number %d : ", i+1);
while (1) {
fgets(buf, sizeof(buf), stdin);
if ((p = strchr(buf, '\n')) != NULL) {
*p = '\0';
}
number[i] = (int)strtol(buf, &p, 10);
if (p == buf || *p != '\0') {
printf("Sorry, [%s] is not a number. Please input number %d : ", buf, i + 1);
} else {
break;
}
}
}
for (i = 0; i < 10; i++) {
printf("\n Number %d is %d", (10-i), number[9-i]);
}
return EXIT_SUCCESS;
答案 1 :(得分:1)
代码也适用于整数。我发现的唯一错误是在打印抱歉邮件时,您只打印i
,它应该是i+1
。
int i = 0, number[10] = {0};
char buf[128] = {0};
for (i = 0; i < 10; i++)
{
printf("Please input number %d : ", i+1);
while(scanf("%d", &number[i]) != 1)
{
scanf("%s", &buf);
printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i+1);
}
}
for (i = 0; i < 10; i++)
{
printf("\n Number %d is %d", (10-i), number[9-i]);
}