Guard scanf from reading too many characters with a define? [duplicate]

余生长醉 提交于 2020-01-14 12:35:30

问题


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?


回答1:


Use defines to stringify:

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

then you can use:

#define MAXLEN 3

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


来源:https://stackoverflow.com/questions/46257499/guard-scanf-from-reading-too-many-characters-with-a-define

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!