相关疑难解决方法(0)

如何使用scanf验证输入

如何使用scanf验证用户输入.现在我有类似的东西,但不起作用.

注意:我有atoi只是为了验证scanf验证是否有效.

scanf("%[0987654321.-]s",buf);

i = atoi(buf);

if(i)
    index = i;
Run Code Online (Sandbox Code Playgroud)

c c++ scanf

5
推荐指数
2
解决办法
2万
查看次数

scanf要求两个值而不是一个

当我编译这段代码时,当我选择A时,它会导致scanf要求两次值.我在这里缺少什么?

这不是第一次遇到这种情况,所以我怀疑我没有抓住scanf的基本内容.

#include <stdio.h>
#include <stdlib.h>

int main()
{

char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");

scanf("%c", &choice);

switch (choice)
{
case 'A':
    {
        int a =0;
        printf("you've chosen menu A\n");
        printf("enter a number\n");
        scanf("%d\n", &a);
        printf("%d\n", a);
    }
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}

return 0;

}
Run Code Online (Sandbox Code Playgroud)

c scanf

3
推荐指数
1
解决办法
369
查看次数

标签 统计

c ×2

scanf ×2

c++ ×1