gpt4 book ai didi

c++ - 我可以在两个字符串的字符串格式中使用两个精度 '*' 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:30 25 4
gpt4 key购买 nike

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

#define SUFF ".txt"
#define MAX_STR 50

fileName[MAX_STR];
name ="myFile"

sprintf( fileName, "%s%s", name, SUFF ); //fileName = "myFile.txt"

现在我想精确地绑定(bind)字符串。

我尝试做的基本事情(但有更多的动态计算,这就是我使用'*'的原因)是:

sprintf( fileName, "%.*s%.*s", 46, 4, name, SUFF );

但是,即使这样也会产生运行时异常。

更具体地说:

sprintf( fileName, "%.*s%.*s",
MAX_STR - (int) sizeof(SUFF), (int) sizeof(SUFF),
name, SUFF );

最佳答案

您的变量参数顺序错误。宽度参数与对象参数一起使用(它必须紧接在对象之前)。

sprintf(fileName, 
"%.*s%.*s",
MAX_STR - (int) sizeof(SUFF), // precision and...
name, // ...object
(int) sizeof(SUFF), // precision and...
SUFF // ...object
);

即使您要使用宽度说明符,使用 snprintf 代替 sprintf 仍然要好得多。

关于c++ - 我可以在两个字符串的字符串格式中使用两个精度 '*' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3835434/

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