仍处于学习模式,可能是以下问题真的很愚蠢,但我不知道为什么会发生..
#include<stdio.h>
int main()
{
/* code to accept string and then a character from stdin */
char str[20], inp;
/*take string from stdin */
printf("string:\n");
scanf("%s",str);
fflush(stdin);
/*input a character */
printf("char:\n");
scanf("%c",&inp);/* code does not reach this point and exits */
}
如评论中所述,在我输入字符串之后,例如。 'strng' 代码在打印 char: 后退出,但它不会等待我输入字符。根据我的理解,我已经给出了足够大的数组大小来存储字符串,如果输入的字符串小于 str 数组的大小,编译器会自动在字符串末尾添加空字符并继续进行.我是不是遗漏了什么或者我的代码有错误。请建议。
谢谢。
最佳答案
尝试移除 fflush(stdin);
并在 scanf("%c",&inp);
关于c - 注意 c 中字符串的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7619106/