gpt4 book ai didi

c - 将 x 个字符附加到字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:42 24 4
gpt4 key购买 nike

我希望下面的行最多从变量 filename 中获取 6 个字符,并将其附加到变量 dmpfilename:

sprintf (dmpfilename, "InstrumentList_FULL.csv_%.*s",6,  filename);
sprintf (dmpfilename, "InstrumentList_FULL.csv_%*s" ,6, filename);
sprintf (dmpfilename, "InstrumentList_FULL.csv_%6s", filename);

但是它们附加了更多的字符(它们将文件名取到'\0')。我究竟做错了什么?

最佳答案

您的第一次尝试应该有效,它使用根据 the manual page 具有正确语义的精度:

This gives [...] the maximum number of characters to be printed from a string for s and S conversions.

对于其他人,您没有做错任何事,只是抱有错误的期望。 manual page明确指出:

In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

您期望截断但没有得到它,因为它不是这样工作的。

我测试了基于精度的那个(使用 %.*s),它运行良好。

关于c - 将 x 个字符附加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22942353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com