for循环和while循环中的scanf

For loop and scanf in a while loop

我这里有一个小的 C 程序,它会一直运行到您输入 ! 字符为止。当您输入感叹号时,它会按预期工作,但当您输入任何其他字符时,会输出一些我无法解释的额外问候语。

int main() {
    char in;
    while (in != '!') {
        printf("\nENTER:\n");
        scanf("%c", &in);
        for (int i = 0; i < 5; i++) {
            printf("hello %c ", in);
        }
    }
}

示例会话:

C:\Users\hp\Desktop>gcc just.c && a.exe

ENTER:
a
hello a hello a hello a hello a hello a 
ENTER:
hello
 hello
 hello
 hello
 hello

ENTER:
!
hello ! hello ! hello ! hello ! hello !

您的代码具有未定义的行为,因为 in 未初始化,因此第一个测试 in != '!' 可能为真,也可能不为真,最终可能对恶意系统造成其他副作用。

您观察到的输出与用户键入键 aEnter![=36 一致=] 和 再次输入

Enter键在stdin中产生一个换行符\n,在第二次迭代中被scanf()读取并输出到循环。第二个和后续 hello 之前有一个 space,因为 printf 格式字符串中 %c 之后有一个 space。

您应该使用 scanf(" %c", &in); 来忽略白色 space 并且您应该测试 scanf() 的 return 值以避免文件末尾的未定义行为。

这是修改后的版本:

#include <stdio.h>

int main() {
    char in = 0;
    while (in != '!') {
        printf("ENTER:\n");
        if (scanf(" %c", &in) != 1)
            break;
        for (int i = 0; i < 5; i++) {
            printf("hello %c ", in);
        }
        printf("\n");
    }
    return 0;
}