【发布时间】:2019-01-11 02:02:21
【问题描述】:
我正在尝试向scanf 传递我想从输入流中读取多少个字符的数字。但是,我无法让它工作。
当我将数字放入代码时,我的代码有效,但我想通过#define 传递数字以轻松更改它。
这行得通:
#include <stdio.h>
int main(void)
{
char tab[11];
printf("Podaj tekst: ");
scanf("%10[^\n]", tab);
printf("%s", tab);
}
这不起作用(它只获取字符直到第一个空白字符):
#include <stdio.h>
#define size 10
int main(void)
{
char tab[size+1];
printf("Podaj tekst: ");
scanf("%size[^\n]", tab);
printf("%s", tab);
}
它不起作用对我来说似乎很奇怪。有什么解决方法可以做我想做的事(除了使用fgets)?
【问题讨论】:
-
"%size[^\n]"与"%s" "ize[^\n]"相同。 -
@chux 有道理,知道如何将“大小”转义到 scanf 中吗?
-
kunek,更好的方法是使用
fgets()并抛弃scanf()。 -
@chux 看起来
fgets()是一个更好的方法,谢谢!
标签: c