打印带有 fprintf 的字符串
Print a string with fprintf
我在打印用于调试目的的字符串时遇到问题。
我像这样创建字符串:
//checker is int
std::stringstream buttonx;
buttonx << "Button" << checker << "_x";
现在我尝试将其打印到我的error.txt
文件中
FILE * p;
p = fopen ("error.txt","w");
fprintf(p, "%s" , buttonx.str());
fclose(p);
输出为:
,æ0
每次都不一样。我不确定发生了什么,希望有人可以解释这个错误?
fopen
是普通的C,不能处理std::string。您需要输入一个 char*
,您可以通过在字符串上调用 .c_str()
来访问它,如下所示:
fprintf(p, "%s", buttonx.str().c_str());
函数 fprintf 需要一个以 null 结尾的字符串(C 字符串);你需要 c_str() 而不是你的:
buttonx.c_str()