我很难理解 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 );
将换行符保留在输入缓冲区中,因为当在某些非空白字符之后遇到第一个空白字符时,%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();
}
(1) 请注意,在 scanf
中使用 %s
非常不安全,您应该将输入限制为缓冲区可以容纳的内容字段宽度,scanf("%99s", command)
将最多读取 99 (sizeof(command) - 1)
) 个字符到 command
,为 0 终止符留出空间。
关于c - 使用 scanf 时 getchar 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54239326/