在 C 中读取字符串时 scanf 的行为
Behavior of scanf when reading strings in C
我想知道编译器在使用 scanf("%s") 时如何处理空格、换行符。我知道 scanf("%s") 无法读取空格和换行符。
例如,如果我输入
hi question
或
hi
question
scanf("%s") 读取它没有问题。
下面是我所指的代码
#include <stdio.h>
int main () {
char str [2][50];
scanf("%s", str[0]);
scanf("%s", str[1]);
printf("%s\n", str[0]);
printf("%s\n", str[1]);
return 0;
}
scanf在线文档:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
我想知道编译器在使用 scanf("%s") 时如何处理空格、换行符。我知道 scanf("%s") 无法读取空格和换行符。
例如,如果我输入
hi question
或
hi
question
scanf("%s") 读取它没有问题。
下面是我所指的代码
#include <stdio.h>
int main () {
char str [2][50];
scanf("%s", str[0]);
scanf("%s", str[1]);
printf("%s\n", str[0]);
printf("%s\n", str[1]);
return 0;
}
scanf在线文档:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).