我很困惑,因为我认为 sprintf 函数返回一个字符串,而它在 cplusplus.com 上显示它返回一个 int?为什么?
基本上,我遇到了以下行的问题,我试图在其中填充一些间距并同时格式化字符串:
printf("%30s", sprintf("1.10f", modeTimeTotal/num_tests));
我得到的错误是:
cannot convert 'double' to 'const char*' for argument '2' to 'int sprintf(char*, const char*, ...)'
最佳答案
sprintf
打印到 一个字符串并返回打印的字符数。 sprintf
调用的第一个参数应该是要打印到的字符串:
char buffer[30];
int n = sprintf(buffer, "%1.10f", modeTimeTotal/num_tests);
printf("Printed %d characters. String is '%s'\n", n, buffer);
您收到警告是因为您试图将 modeTimeTotal/num_tests
硬塞进 sprintf
的格式字符串参数中。
关于关于 sprintf 函数如何在 C 中工作的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767976/