C语言scanf语法帮助

3
当我运行以下代码片段时,它会一直运行到第二个问题。然后将“客户是否为学生?(y / n)\n”和“电影时间是多少?(以小时为单位)\n”提示放在一起(它们之间没有回答区域)。如果从那里采取任何行动,程序将停止工作。我做错了什么?(我很确定这与语法有关)
int A,B,C,D,age,time;
char edu, ddd;

printf ("What is the customer's age? \n");
scanf("%d", &age);

printf ("Is the customer a student? (y/n) \n");
scanf("%c", &edu);

printf ("What is the movies time? (in hours) \n");
scanf("%d", &time);

printf ("Is the movie 3-D? (y/n) \n");
scanf("%c", &ddd);

2
这个可能会有帮助:https://dev59.com/IXI-5IYBdhLWcg3wy70d - sje397
1
最好避免使用 scanf:http://c-faq.com/stdio/scanfprobs.html - jamesdlin
6个回答

4
您可能需要在每个scanf后面吃掉来自stdin的额外输入,以便它不会留在缓冲区中并导致scanf接收缓冲数据。
这是因为在输入第一个文本条目后按Enter键产生的换行符留在缓冲区中,并且是“%c”格式的有效条目-如果查看“edu”的值,您应该发现它是一个换行符。

4
使用scanf读取输入时,输入在按下回车键后被读取,但回车键生成的换行符未被scanf消耗,这意味着下一次从标准输入中读取时将有一个换行符准备好被读取。
避免这种情况的一种方法是使用fgets将输入读取为字符串,然后使用sscanf提取所需内容。
消耗换行符的另一种方法是使用scanf("%c%*c",&edu);%*c将从缓冲区中读取换行符并将其丢弃。

2
您可以在%c前添加一个空格。这是必要的,因为与其他转换说明符不同,它不会跳过空格。所以当用户输入像"10\n"这样的年龄时,第一个scanf读取到10的结尾。然后,%c读取换行符。空格告诉scanf在读取字符之前跳过所有当前的空格。
printf ("What is the customer's age? \n");
scanf("%d", &age);

printf ("Is the customer a student? (y/n) \n");
scanf(" %c", &edu);

printf ("What is the movies time? (in hours) \n");
scanf("%d", &time);

printf ("Is the movie 3-D? (y/n) \n");
scanf(" %c", &ddd);

2

如果使用scanf和"%c"时遇到任何问题,请参考@jamesdlin的建议。 "time"是C标准库函数的名称,最好使用其他名称,例如:

int A,B,C,D,age=0,timevar=0;
char edu=0, ddd=0, line[40];

printf ("What is the customer's age? \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%d", &age) ) age=0;

printf ("Is the customer a student? (y/n) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%c", &edu) ) edu=0;

printf ("What is the movies time? (in hours) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%d", &timevar) ) timevar=0;

printf ("Is the movie 3-D? (y/n) \n");
if( fgets(line,40,stdin) && 1!=sscanf(line,"%c", &ddd) ) ddd=0;

在最后,您的变量将具有一个已定义的内容,输入错误为0,否则不等于0。

1
使用 fflush(stdin); 语句清除 stdin 缓冲区内存,以便在读取任何字符数据之前清除缓冲区,否则它会将第一个 scanf 的回车键值读入第二个 scanf。

0

我试了一下你的程序,发现在输入年龄后,当我按回车键时,它会将其作为下一个scanf(即&edu)的输入,并且对于第三个和第四个问题也是同理。我的解决方案可能很幼稚,但你可以简单地在每个scanf后使用缓冲scanf来吸收“Enter”。或者直接这样做:

scanf(" %c", &variable);

(格式字符串中的任何空格都会使 scanf 吸收所有后续连续的空格)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接