使用 scanf 的最大字符串长度 ->ANSI C [英] Max string length using scanf -> ANSI C

查看:24
本文介绍了使用 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[^
]s",sometext)

我试过了:

scanf("%MAX_STR_LEN[^
]s",sometext)
scanf("%"MAX_STR_LEN"[^
]s",sometext)
scanf("%",MAX_STR_LEN,"[^
]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)"[^
]s", sometext)

也许 VS2010 提供了类似的东西?

Maybe VS2010 offers something similar?

这篇关于使用 scanf 的最大字符串长度 ->ANSI C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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