我想从用户那里得到一个最大长度为30个字符串的输入,并检查它是否包含行尾.
这是我到目前为止所写的内容:
int main(void) {
int i;
char* command = (char*)calloc(31, sizeof(char));
while (0 < 1) {
scanf("%s", command);
for (i = 0; i <= strlen(command); ++i) {
if (command[i] == '\n')
printf("here");
}
if (strcmp(command, "quit") == 0)
break;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是检查用户提供的命令是否为"合法" - 长度<31.当我运行此代码时,无论输入的长度如何,它都不会打印"here".
scanf不包括终止'\n',但fgets确实:
换行符使fgets停止读取,但它被认为是有效字符,因此它包含在复制到str的字符串中.
只需将您的scanf行更改为:
fgets(command, 31, stdin);
Run Code Online (Sandbox Code Playgroud)