将int转换为const char*以便写入文件
convert int to const char* in order to write on file
我在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 *
相关文章:
- 将 boost::文件系统::p ath 转换为 char?
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 将.txt文件存储到 char* 2d 矢量C++中
- 将文本文件读取为 const char* 有时有效,有时无效
- C 通过char读取文件字符串的文件char;崩溃
- 如何通过C 读取CHAR的文件字符
- C 如何读取从文件到char数组的文本行
- 如何使用 C++ 中的写入函数将浮点转换为 char 以写入文件
- 如何修复此 OpenCV 错误:断言失败((无符号)i < (无符号)cn) 在 cv::Vec<unsigned char,3>:::运算符 (), 文件
- C 字符串到C char数组,以写入二进制文件
- 为什么使用char数组来存储以二进制模式打开的文件的内容
- 如何将足够的数据从文本文件分配到char*中,然后将其复制到内存C 中
- 想要在读取文件时在类型的char上使用atoi()
- 在 c++ 中将整个.txt文件复制到 char 数组中
- 从一个文本文件加载多个 char 和 int 类型的数组
- C :如何以快速方式读取Char文件
- C++ 中的文件处理错误 - 调用"std::basic_fstream<char, std::char_traits<char> >::open(const char[8],
- 从文本文件读取到 char* 数组
- 在C++中读取二进制文件时将char*转换为double