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

夙愿已清 提交于 2019-12-25 19:57:16

问题


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);

Thanks in advance


回答1:


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

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;



回答2:


Try itoa(a) it converts an i nt to a rray hence itoa




回答3:


What's wrong with fprintf? Or snprintf and then fputs the result.




回答4:


Use type-casting. You can use boost::lexical_cast

Once in a string, you can use the c_str() member function to get a const char *



来源:https://stackoverflow.com/questions/7934907/convert-int-to-const-char-in-order-to-write-on-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!