使用 scanf 时 getchar 不会停止

2024-03-26

我很难理解getchar()。在下面的程序中getchar按预期工作:

#include <stdio.h>


int main()
{
    printf("Type Enter to continue...");
    getchar();
    return 0; 
} 

然而,在下面的程序中,getchar不会产生延迟并且程序结束:

#include <stdio.h>

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

我有以下奇怪的解决方法,它有效,但我不明白为什么:

#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;    
}

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

raw_input("Type Enter to continue")

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

scanf("%s", command );

leaves the newline in the input buffer, since the %s(1) format stops when the first whitespace character is encountered after some non-whitespace, getchar() then returns that newline immediately and doesn't need to wait for further input.

您的解决方法有效,因为它在调用之前从输入缓冲区中清除换行符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();
}

(1) Note that using %s in scanf is very unsafe, you should restrict the input to what your buffer can hold with a field-width, scanf("%99s", command) will read at most 99 (sizeof(command) - 1)) characters into command, leaving space for the 0-terminator.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 scanf 时 getchar 不会停止 的相关文章

随机推荐