为了创建格式化文件,我想使用fprintf
。它必须得到 char*
参数,但我有几个字符串变量。如何使用 fprintf
?
最佳答案
fprintf
与字符串的基本用法如下所示:
char *str1, *str2, *str3;
FILE *f;
// ...
f = fopen("abc.txt", "w");
fprintf(f, "%s, %s\n", str1, str2);
fprintf(f, "more: %s\n", str3);
fclose(f);
您可以使用多个 %s
格式说明符添加多个字符串,并且可以重复调用 fprintf
以增量写入文件。
如果您有 C++ std::string
对象,您可以使用它们的 c_str()
方法来获取适合使用的 const char*
使用 fprintf
:
std::string str("abc");
fprintf(f, "%s\n", str.c_str());
关于c - 带有字符串参数的 fprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018730/