scanf:内部带有宏(#define 常量)的模板 [英] scanf: template with macro (#define constant) inside

查看:62
本文介绍了scanf:内部带有宏(#define 常量)的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些像这里的代码:

I have a bit of code like here:

#define MAXSIZE 100

int main() {
    char str[MAXSIZE+1];
    scanf("%100s", str);
    ...

问题是我仍然有幻数"100,虽然定义了 MAXSIZE.有没有办法将 MAXSIZE 正确插入"到 scanf 格式字符串中?(纯C,c-99标准)

The problem is I still have "magic number" 100, although defined MAXSIZE. Is there a way to properly "insert" MAXSIZE into scanf format string? (pure C, c-99 standart)

推荐答案

有,但最好使用 fgets():

if (fgets(str, sizeof str, stdin) != NULL) {
    // process input
}

这样做的好处(除了毫无疑问的可读性提升之外)是 fgets() 可以正确处理大小, i.e.它考虑了终止字符 0(scanf() 没有),因此您不必在声明缓冲区时在大小上加一.它也总是为您 NUL 终止数组.更不容易出错.

The good thing about this (apart from an undoubted readability boost) is that fgets() takes care of the size correctly, i. e. it accounts for the terminating 0 character (which scanf() doesn't), so you don't have to hack around with adding one to the size when declaring your buffer. It also always NUL-terminates the array for you. Way less error prone.

至于原始问题:尝试通常的字符串化"技巧:

As to the original question: try the usual "stringify" trick:

#define REAL_STRINGIFY(x) #x
#define STRINGIFY(x) REAL_STRINGIFY(x)

scanf("%" STRINGIFY(MAXSIZE) "s", str);

但这很丑,不是吗?

这篇关于scanf:内部带有宏(#define 常量)的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆