Mac 上的 C 程序运行出乎意料

问题描述

我有这个小程序

#include <stdio.h>

int main(){
    int c;
    while(c != EOF){
        printf("Enter character\n");
        c = getchar();
        printf("Character: %c\n",c);
    }
    printf("FIN\n");
    return 0;
}

终端的输出看起来很奇怪,因为在输入一个字符后,while 循环会被执行两次:

Enter character
a
Character: a                //This should be the last output after a char was entered,but the loop gets executed a second time without waiting for a keyboard-input:
Enter character
Character: 

Enter character

 

在终端中,我正在编译和运行这样的代码

gcc main.c
./a.out

我做错了什么?

感谢您的回答,这是由 enter 输入的 lf .... 太明显了 :D

解决方法

您正在输入 2 个字符,'a' 和一个 LF。

直到两者都被处理后才会进行 while 测试。

,

对于初学者来说,你的程序有未定义的行为,因为你在 while 循环的条件下使用了未初始化的变量 c

int c;
while(c != EOF){
//...

函数 getchar 还读取空格字符,例如按 Enter 键后放置在缓冲区中的换行符 '\n'

另一个问题是你在读取和输出它之后检查变量c

while(c != EOF){
    printf("Enter character\n");
    c = getchar();
    printf("Character: %c\n",c);
}

例如,您应该使用 getchar 而不是 scanf

char c;

while ( scanf( " %c",&c ) == 1 )
{
    //...
}

注意转换说明符 %c 前的空格。此空格表示将跳过空白字符。

,

只要您按下 enter,一个换行符就会添加到输入流中。所以你的程序实际上读取了两个字符:a\n。这个换行符由 getchar() 读取并在第二次迭代中分配给 c,您实际上可以看到它被打印为空行。在打印 c 之前,您可以使用 break 语句退出循环:if (c == '\n') break;

如果你输入abc,你会看到在c之后打印了一个空行。