scanf() 可变长度说明符 [英] scanf() variable length specifier

查看:29
本文介绍了scanf() 可变长度说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用变量来指定 scanf() 应该读入的最大字符数?

How can I use a variable to specify the max number of chars scanf() should read in?

例如使用 printf() 你可以像这样使用 *

For example using printf() you can use the * like so

#define MAXVAL 5
printf("Print at maximum MAXVAL chars: %.*s\n", MAXVAL, "myStringHere");

这只会打印 5 个字符,如何让 scanf 只能在 MAXVAL 中读取?MAXVAL 必须用作长度说明符.我不能简单地做

This will only print 5 chars, how can I make scanf only read in MAXVAL? MAXVAL must be used as the length specifier. I cannot simply do

scanf("%5s", string);

现在我只能想到使用 scanf 读入一个大数组,然后使用 ssprintf 将字符串存储到我的长度限制字符串中.然而,使用长度说明符会容易得多.

Right now I can only think of reading into a large array using scanf then using ssprintf to store the string into my length limited string. Using a length specifier would be so much easier however.

推荐答案

您可以使用 C 预处理器来帮助您.

You can use the C preprocessor to help you with that.

#define STR2(x) #x
#define STR(X) STR2(X)
scanf("%" STR(MAXVAL) "s", string);

处理器将 "%" STR(MAXVAL) "s" 组合成 "%5s"

这篇关于scanf() 可变长度说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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