将int转换为const char *,以便写入文件 [英] convert int to const char* in order to write on file

查看:627
本文介绍了将int转换为const char *,以便写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中有以下代码,我想将一个整数转换为一个const char *,以便写入一个文件。我试过itoa或sstream函数,但它不工作。

I have the following code in C++ and I would like to convert a integer to a const char* in order to write on a file. I tried itoa or sstream functions but it's not working.

FILE * pFile;
pFile = fopen ("myfile.txt","w");

int a = 5;

fputs (&a,pFile);
fclose (pFile);

提前感谢

推荐答案

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

The first parameter to fputs is a char*, so the code you show is obviously incorrect.

你说我试过itoa或sstream函数,但它不工作。 / em>解决方案,没有理由让他们不工作。

You say I tried itoa or sstream functions but it's not working. but those are the solutions, and there's no reason for them not to work.

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;

这篇关于将int转换为const char *,以便写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆