c - 默认情况下,读取输入缓冲区中的哪个字符会使 scanf() 停止读取字符串?

标签 c string input scanf

当我不使用任何扫描集或否定扫描集时,遇到缓冲区中的哪个字符会使 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/

相关文章:

c# - 为什么我不能利用计算机中的 4GB RAM 来处理 C# 中少于 2GB 的信息?

html - 停止响应 href 链接的 html 输入

c++ - 混合使用 C 和 C++ 时出现重复符号

c - C中字符串的所有可能组合

java - 字符串到字节然后 byte[] 0xformat

delphi - Delphi字符串中的字符如何转义

java - 扫描仪字符串困惑

javascript - React - 输入失去按键焦点

C : How to use a struct, 在函数 A 中声明和定义,在另一个函数 B 中

python - 使用 AES 在 C 中加密并在 Python 中解密