带字符串参数的 fprintf [英] fprintf with string argument
本文介绍了带字符串参数的 fprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了创建格式化文件,我想使用fprintf
.它必须获得 char*
参数,但我有几个字符串变量.如何使用 fprintf
?
In order to create a formatted file, I want to utilize fprintf
. It must get char*
parameters, but I have several string variables. How can I use fprintf
?
推荐答案
fprintf
与字符串的基本用法如下所示:
The basic usage of fprintf
with strings looks like this:
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
来增量写入文件.
You can add several strings by using several %s
format specifiers and you can use repeated calls to fprintf
to write the file incrementally.
如果您有 C++ std::string
对象,您可以使用它们的 c_str()
方法来获得适合使用的 const char*
使用 fprintf
:
If you have C++ std::string
objects you can use their c_str()
method to get a const char*
suitable to use with fprintf
:
std::string str("abc");
fprintf(f, "%s\n", str.c_str());
这篇关于带字符串参数的 fprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文