使用scanf时getchar不会停止

Oz1*_*123 7 c getchar

我很难理解getchar().在以下程序中getchar按预期工作:

#include <stdio.h>


int main()
{
    printf("Type Enter to continue...");
    getchar();
    return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

但是,在以下程序中,getchar不会产生延迟并且程序结束:

#include <stdio.h>

int main()
{
    char command[100];
    scanf("%s", command );
    printf("Type Enter to continue...");
    getchar();
    return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

我有以下的解决方法,这是有效的,但我不明白为什么:

#include <stdio.h>

int main()
{
    char command[100];
    int i;
    scanf("%s", command );
    printf("Type Enter to continue...");
    while ( getchar() != '\n') {
      i=0; 
    }
    getchar();
    return 0;    
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:
1.在scanf做什么?为什么这样scanf做?
2.为什么我的工作在工作?
3.模拟以下Python代码的好方法是什么:

raw_input("Type Enter to continue")
Run Code Online (Sandbox Code Playgroud)

Dan*_*her 10

输入仅在您输入换行符后发送到程序,但是

scanf("%s", command );
Run Code Online (Sandbox Code Playgroud)

将换行符保留在输入缓冲区中,因为%s(1)格式在某个非空格后遇到第一个空白字符时停止,getchar()然后立即返回该换行符,不需要等待进一步的输入.

您的解决方法有效,因为它会在getchar()再次调用之前清除输入缓冲区中的换行符.

要模拟行为,请在打印消息之前清除输入缓冲区,

scanf("%s", command);
int c;
do {
    c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
    // input stream ended, do something about it, exit perhaps
} else {
    printf("Type Enter to continue\n");
    getchar();
}
Run Code Online (Sandbox Code Playgroud)

(1)注意使用%sin scanf是非常不安全的,你应该将输入限制为缓冲区可以用字段宽度保存的scanf("%99s", command)内容,最多可以读取99(sizeof(command) - 1))个字符command,为0终止符留出空间.