使用scanf的最大字符串长度 - > ANSI C [英] Max string length using scanf -> ANSI C
本文介绍了使用scanf的最大字符串长度 - > ANSI C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
#define MAX_STR_LEN 100
我要投入到 scanf函数
模式,所以我可以控制字符串的长度:
and I want to put into scanf
pattern so I can control the string length:
scanf("%100[^\n]s",sometext)
我试过:
scanf("%MAX_STR_LEN[^\n]s",sometext)
scanf("%"MAX_STR_LEN"[^\n]s",sometext)
scanf("%",MAX_STR_LEN,"[^\n]s",sometext)
和它没有工作。我只是想避免缓冲区溢出,因为SomeText则会与分配的malloc(MAX_STR_LEN)
...
And it didn't work. I just want to avoid buffer overflow since "sometext" is allocated with malloc(MAX_STR_LEN)
...
任何想法?
推荐答案
我是不是高兴与任何这些解决方案,让我进一步研究,并发现了GNU GCC宏观的字符串化
I wasn't happy with any of these solutions, so I researched further, and discovered GNU GCC macro stringification
可使用的为:
#define XSTR(A) STR(A)
#define STR(A) #A
#define MAX_STR_LEN 100
scanf("%"XSTR(MAX_STR_LEN)"[^\n]s", sometext)
也许VS2010提供类似的东西?
Maybe VS2010 offers something similar?
这篇关于使用scanf的最大字符串长度 - > ANSI C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文