2010-09-16 76 views
3

当我运行下面的代码片段时,它会运行到第二个问题。然后它将“客户是学生吗?(y/n)\ n”和“什么是电影时间?(以小时为单位)\ n”一起提示(没有区域来回答他们之间的问题)。如果从那里采取任何行动,程序将停止工作。我做错了什么? (我敢肯定它的语法关系)使用C scanf语法的帮助

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

[This](http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c)可能会有所帮助。 – sje397 2010-09-16 04:45:29

+1

最好避免使用'scanf':http://c-faq.com/stdio/scanfprobs.html – jamesdlin 2010-09-16 05:52:44

回答

4

你可能需要在每次scanf函数后吃从标准输入额外的输入,所以它不会在缓冲区坚持围绕并导致scanf函数接收缓存数据。

这是因为在第一个文本输入后输入的换行符保留在缓冲区中并且是“%c”格式的有效输入 - 如果查看“edu”的值,您应该发现它是换行符字符。

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); 
4

当读取使用scanf输入,按下后返回键,而是由返回键生成的新行不被scanf,这意味着未来你从标准输入读取会有时间消耗的输入被读取准备阅读的换行符。

避免的一种方法是使用fgets将输入读取为字符串,然后使用sscanf提取您想要的内容。

消耗换行符的另一种方法是scanf("%c%*c",&edu);%*c将从缓冲区读取换行符并丢弃它。

2

scanf和“%c”有任何问题,请参阅:@jamesdlin。 “时间”是一个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);

声明明确标准输入的缓冲存储器中读取任何字符数据

之前,否则它会读取到第二scanf函数的输入第一个scanf函数的键值。

0

我想你的计划,似乎打字岁以后,当我按下回车键,认为作为输入下一个scanf函数(即用于& EDU)同样地,对于第三和第四个问题。我的解决方案可能很幼稚,但你可以简单地在每一个缓冲区之后使用缓冲区scanf来吸收“Enter”。或干脆这样做

scanf(" %c", &variable); 

(格式字符串中的任何空格将使scanf吸收所有更多的连续空格)。