格式化带有多个百分号的字符串 [英] Format string with multiple percent signs

查看:273
本文介绍了格式化带有多个百分号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 %% 用于转义字符串中的实际标记,因此 %%% ds 将在以下格式字符串中以%10s 结尾,但是我不知道为什么我需要 %% 5s 是否在此字符串中?

I know %% is used to escape actual % signs in a string, so %%%ds will end up with %10s in the following format string, but I don't know why I need %%5s in this string?

毕竟,只有两个附加参数(BUFFSIZE / 10)。

After all, there are only two additional arguments (BUFFSIZE / 10).

#define BUFFSIZE 100
char buf[100]={0}
sprintf(buf, "%%5s %%%ds %%%ds", BUFFSIZE / 10, BUFFSIZE / 10);

运行上面的代码后,buf将包含字符串,

After running the code above, the buf will contain the string,

%10s %10s 


推荐答案

目的是获取一个格式字符串以在需要诸如 sscanf()之类的格式字符串的另一个函数中使用它。

The purpose is to get a format string to use it in another function that needs a format string like sscanf().

使用您的代码,您将得到:%5s%10s%10s 写入您的 buf 参见在线,这意味着它将接受三个带有长度标识符的字符串。

With your code you get: %5s %10s %10s written to your buf, see online, which means it will accept three strings with a length identifier.

%%5s          --> %5s
%%%ds with 10 --> %10s (read it that way: {%%}{%d}{s})

现在可以在 sscanf()调用中使用缓冲区%5s%10s%10s ,如所示此处

That buffer %5s %10s %10s could now be used in a sscanf() call like shown here.

但是有一种最佳做法是防止引起缓冲区溢出由 sscanf()编写,Kernighan和Pike在他们的书编程实践,请参见此处的SO

But there is a best practice to prevent a buffer overflow caused by sscanf() which is also described by Kernighan and Pike in their book The Practice of Programming, see here on SO.

您可能无法使用%* s 可能是,请参见在此处找到

The reason why you maybe can't use %*s may be, see here on SO:


对于 printf ,*允许您通过附加参数指定最小字段宽度,即 printf(%* d ,4,100); 指定一个国际剑联ld宽度为4。

For printf, the * allows you to specify minimum field width through an extra parameter, i.e. printf("%*d", 4, 100); specifies a field width of 4.

对于 scanf ,*表示要读取但忽略该字段,因此即输入 12 34的 scanf(%* d%d,& i)将忽略12并将34读为整数i。

For scanf, the * indicates that the field is to be read but ignored, so that i.e. scanf("%*d %d", &i) for the input "12 34" will ignore 12 and read 34 into the integer i.

这篇关于格式化带有多个百分号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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