将int转换为const char*以便写入文件

convert int to const char* in order to write on file

本文关键字:文件 char int 转换 const      更新时间:2023-10-16

我在c++中有以下代码,我想将整数转换为const char*,以便在文件上写入。我尝试了itoa或sstream函数,但它不起作用。

FILE * pFile;
pFile = fopen ("myfile.txt","w");
int a = 5;
fputs (&a,pFile);
fclose (pFile);

Thanks in advance

fputs的第一个参数是char*,因此您显示的代码显然是不正确的。

你说I tried itoa or sstream functions but it's not working.,但这些的解决方案,没有理由不工作。

int a = 5;
//the C way
FILE* pFile = fopen("myfile.txt","w");
char buffer[12];
atoi(a, buffer, 10);
fputs(buffer, pFile); 
fclose (pFile);
//or
FILE* pFile = fopen("myfile.txt","w");
fprintf(pfile, "%d", a);
fclose(pfile);
//the C++ way
std::ofstream file("myfile.txt");
std::stringstream ss;
ss << a;
file << ss.str();
//or
std::ofstream file("myfile.txt");
file << a;

试试itoa(a),它将i nt 转换为一个数组,因此itoa

fprintf怎么了?或snprintf,然后fputs的结果

使用类型转换。您可以使用boost::lexical_cast

在字符串中,您可以使用c_str()成员函数来获取const char *