【问题标题】:Trying to pass maximum number of characters read by scanf through #define尝试通过#define传递scanf读取的最大字符数
【发布时间】: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)?

【问题讨论】:

标签: c


【解决方案1】:

您可以使用预处理器# 运算符将数字或其他文本转换为字符串。这需要使用两个宏,一个用于扩展size 宏,另一个用于应用运算符:

#define size 10

#define StringifyHelper(x)  #x
#define Stringify(x)        StringifyHelper(x)

...

char tab[size+1];
scanf("%" Stringify(size) "[^\n]", tab);

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2019-01-26
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2012-03-31
    • 1970-01-01
    相关资源
    最近更新 更多