防止scanf读取带有定义的太多字符? [英] Guard scanf from reading too many characters with a define?

查看:63
本文介绍了防止scanf读取带有定义的太多字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我使用一个字符串大小的定义,但是当我使用 scanf()时,我想防止该函数读取太多字符(并且为空终止符保留空间)。我想知道是否可以使用我的定义来执行此操作,而不是使用硬编码的幻数...

Usually, I use a define for the size of a string, but when I use scanf(), I want to guard the function from reading too many characters (and reserve space for the null-terminator). I was wondering whether I could do this using my define, instead of a hardcoded magic number...

#include <stdio.h>

#define MAXLEN 4

int main(void) {
    char a[MAXLEN];
    scanf("%3s", a); // Can I do that with 'MAXLEN' somehow?
}

有可能吗?如果是,怎么办?

Is it possible? If yes, how?

推荐答案

使用定义进行字符串化:

Use defines to stringify:

#define LENSTR_(x) #x
#define LENSTR(x) LENSTR_(x)

然后您可以使用:

#define MAXLEN 3

char a[MAXLEN + 1];
scanf("%" LENSTR(MAXLEN) "s", a);

这篇关于防止scanf读取带有定义的太多字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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