请帮助我在程序中找到错误

时间:2013-12-19 09:04:28

标签: c

我知道我发布的程序非常基本,但我无法找到错误。我重新检查了所有内容,但是尽管没有编译错误,输出仍未到来。

#include<stdio.h>
#include <stdlib.h>
int main()
{
    int i;
    while(1)
    {
        if((scanf("%d",&i))!=42)
        {
            printf("%d",i);
        }
        else
        {
            break;
        }
    } 
    return 0;
}  

感谢您的时间和考虑。

2 个答案:

答案 0 :(得分:7)

scanf不会返回输入的值。它返回匹配的输入数。所以42的检查是不正确的。如果为i分配了整数,则返回1;如果输入无效,则返回0。如果要在用户输入42时退出循环,则应明确测试if (i == 42)

作为simonc mentioned,您没有获得任何输出的原因是因为printf("%d",i);未在数字后面打印换行符"\n",而标准输出stdout )流is line-buffered。这意味着标准库将继续缓冲printf s,直到遇到换行符。此时缓冲区将刷新到控制台。

解决方案是添加换行符(这可能是你想要的):printf("%d\n",i);或者,你可以调用fflush(stdout)告诉std库立即将缓冲的内容刷新到控制台。或者,写入stderr将立即输出,因为它无缓冲


这应该证明:

#include <stdio.h>

int main()
{
    int i;
    while(1) {
        fprintf(stderr, "Enter a number (or 42 to quit): ");
        if((scanf("%d",&i)) != 1) {
            fprintf(stderr, "Invalid input.\n");
            continue;
        }
        if (i==42)
            break;

        printf("Number provided: %d\n", i);
    }
    return 0;
}

输出:

$ ./a.exe
Enter a number (or 42 to quit): 17
Number provided: 17
Enter a number (or 42 to quit): 42
$ 

答案 1 :(得分:0)

您正在将scanf函数的返回值与42进行比较,而不是将变量i's值进行比较。 也许你应该读这个 http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf