第一个fprintf()可以正常工作,但是第二个输出整个废话
#include <string>
int main()
{
FILE* f;
fopen_s(&f, "text.txt", "w");
std::string name = "hello";
int area = 123;
char ch = 'i';
fprintf(f, "abc"); // OK
fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch); // not OK
}
最佳答案
%s
格式说明符期望以NULLt终止的char
数组,而不是std::string
。因此,fprintf
的行为是不确定的。
使用:fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch);
因为c_str()
函数返回以null结尾的数组。
此外,其他类型的格式字符串似乎也不正确。要打印int
,格式说明符是%d
,而不是%c
,并且为char指定的格式是%c
,而不是%d
。
因此,对fprintf
的最终调用应为:fprintf(f, "|%-12s |%-5d |%-9c |", name.c_str(), area, ch);
关于c++ - 为什么我的代码中的fprintf()函数无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61198130/