当我不使用任何扫描集或否定扫描集时,遇到缓冲区中的哪个字符会使 scanf()
停止从缓冲区读取数据(假设字符数组足够大)?答案似乎是空白,因为如果我们在输出中输入一个多词句子,那么默认情况下 scanf()
只存储第一个单词,但是当我运行这段代码时:
int main(void) {
char n[20];
int status;
do {
status = scanf("%[^ ]", n);
//status = scanf("%s", n);
printf("%d %s\n", status, n);
} while (status);
return 0;
}
并输入hello world
并按回车键,输出为:
1 hello
0 hello
当我将 do
-while
更改为:
do {
//status = scanf("%[^ ]", n);
status = scanf("%s", n);
printf("%d %s\n", status, n);
} while (status);
我得到这个作为输出(对于相同的输入):
1 hello
1 world
程序无法自行终止
同样,对于第一个 do
-while
,如果我输入 hello
并按回车,我没有得到任何输出,程序也没有' 终止(显然是因为它没有读取空间)。但是第二个do
-while
不是这种情况。
另外,如果有人能回答我如何更改我的代码以使其在按下返回键时终止,同时一次存储一个单词,那就太好了。
最佳答案
By default, reading which character in the input buffer makes scanf() stop reading a string?
没有默认值。
scanf()
何时/如何停止取决于格式。当遇到文件末尾或输入错误时,读取也会停止。
// format "%c"
// Reads 1 character, then stops, no special value stops it early.
char ch;
scan("%c", &ch);
// format "%9[^ ]"
// Reads up to 9 non-space characters, then stops. Even reads a null character.
char buf[10];
scan("%9[^ ]", buf);
// format "%9s"
// Reads and discards leading white-space characters,
// then reads/saves up to 9 non-white-space characters, then stops.
// Even reads a null character.
char buf[10];
scan("%9s", buf);
// format "xyz"
// Reads up to 3 characters that match the pattern "xyz", then stops.
scan("xyz");
关于c - 默认情况下,读取输入缓冲区中的哪个字符会使 scanf() 停止读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783081/