Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 views
in Technique[技术] by (71.8m points)

c++ - convert int to const char* in order to write on file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...