【发布时间】:2020-03-06 00:24:51
【问题描述】:
言归正传,我是 C 语言的初学者,刚刚在 C 程序中遇到了一种输入字符串的奇怪方法:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char ch, string[100], sent[100];
scanf("%c", &ch);
scanf("%s", &string);
scanf("%[^\n]%*c", &sent);
printf("%c\n", ch);
printf("%s\n", string);
printf("%s", sent);
return 0;
}
这是错误:最后一行(句子)不打印,不知道我错在哪里,但在研究中我发现了这段代码:
scanf(" %[^\n]%*c", &sent); //not theres a space before %[^\n]%*c; and then it worked (wtf)
你能解释一下为什么只在其中添加一个空格就可以工作吗?
【问题讨论】:
-
这是因为每个说明符
%之后的*告诉scanf不要存储结果。编译器说“警告C4474:'scanf':为格式字符串传递的参数太多。” -
@WeatherVane 但是在 "%*[^\n]%*c" 之前放置 1 个空格如何解决所有问题,在放置空间之后代码可以完美运行
-
我不知道:编译器仍然给出警告。除了:
&string和&sent应该是string和sent反正。无论如何,如果不说您输入的内容,就无法评论“完美无缺”的含义。 -
我正在以黑客级别练习此代码,我知道“&”不应该存在,但没有它,他们的编译器会显示错误
-
您的代码有未定义的行为。它尝试打印一个未初始化的字符串。
标签: c output scanf format-specifiers