2011-10-19 123 views
2

我的一个朋友正在尝试学习c(她自己和一本书),有时她会寻求帮助。我不明白为什么我不能在c中得到三个输入

她只是给了我一些我无法回答的东西;我很惭愧,但我在大学学习了C,然后转移到了PHP。我很困难,所以我想知道为什么我们不能得到三个输入。这里的部分代码:

#include <stdio.h> 

int main() 
{ 
    int num1; 
    int num2; 
    char x; 

    printf("Enter a number:\n"); 
    scanf("%d\n",&num1); 
    printf("Enter another number:\n"); 
    scanf("%d\n",&num2); 
    printf("Choose an operation sign:\n"); 
    scanf("%c\n",&x); 

... 

喜欢这个询问的第一个输入两次,就像这样:

Enter a number: 
1 
2 
Enter another number: 
3 
Choose an operation sign: 
- 

如果我删除它跳过最后一个scanf\n

你能帮我理解为什么吗?

+0

注意,上面的例子输入,你会得到'num1 == 1','num2 == 2','x =='3''。 –

+1

如果您删除\ n,程序不会跳过上一次scanf。相反,\ scanf中仍留在缓冲区中的\ n存储在变量x中。 – Farhan

回答

4

这里阅读:scanf() leaves the new line char in buffer?

解决方案:

int main() 
{ 
    int num1; 
    int num2; 
    char x; 

    printf("Enter a number:\n"); 
    scanf("%d",&num1); 
    printf("Enter another number:\n"); 
    scanf("%d",&num2); 
    printf("Choose an operation sign:\n"); 
    scanf("\n%c",&x); /* See the \n <---------------- */ 
} 

一种替代方案:

char buf[2]; /* We need 2 characters for the null */ 
scanf("%1s", buf); /* We ask max 1 character (plus null given by scanf) */ 
char x = buf[0]; /* We take the first character */ 

作为一个小纸条,感谢如何scanf的作品,同时与解决方案,您可以直接插入在第一个“输入”中的所有数据和各种scanf将采取他们的一部分。所以你可以插入123 234 +,它会被正确地分成三个变量。

+2

看到这个问题的另一种方式,以确保所有的垃圾从标准偏差之间刷新: [我无法刷新标准输入](http://stackoverflow.com/questions/2187474/i-am-not-able-to -flush-stdin) –

+0

@Daniel最后没有“便携”解决方案。即使C FAQ告诉它,并建议替代http://c-faq.com/stdio/stdinflush2.html – xanatos

+0

@xanatos您列出的C常见问题解答页面有一个用于清除缓冲区的可移植代码片段:P – Farhan

0

您也可以尝试使用fflush,但它取决于库实现(stdio)。 它的C参考可以找到here

我稍后会对此进行测试并更新我的帖子,并说明它是否有效。

+0

在输入流上调用fflush会导致未定义的行为。 – Farhan

+0

取决于编译器,VC清空输入流。当然,这是非常不便携的。 – SvenS

+0

不在编译器上,而是实际的库实现(如参考资料中所述)。这意味着更新库时行为可能会发生变化。但出于学习目的,您可以使用它,因为它不是一个生产环境,您可能需要长期支持或可移植性。 –

1

是,scanf不会删除换行,你不能刷新stdin,所以这个怎么样:

int num1; 
char nleater; 
printf("Enter a number:\n"); 
scanf("%d%c", &num1, &nleater); 

或确实这样:

printf("Enter number sign number: "); 
scanf("%d %c %d",&num1,&x,&num2); 
printf("%d %c %d", num1, x, num2); 
相关问题