Using fputs with an argument of type string
Question
I'm using fputs in C++ to write a string in a file.
fputs (const char*, FILE*);
If I use a simple statement like,
fputs ("information", pFile);
everything is ok and "information" will be written in the file. But if I write a variable of type,
std::vector<std::string>
into the file, some non-ascii characters are stored in the file. Do I have to use a method to convert type std::vector<std::string>
into a format which fputs can recognize ?
Solution
Use
fprintf ( pFile, "%s", iterVar.at(currentRun).c_str() )
instead of
fprintf ( pFile, "%s", iterVar.at(currentRun).data() )
You don't want to use data()
ever as it is missing the trailing \0
.
(This code is based on the questioner's comment on @GregHewgill's answer, where iterVar
is of type vector<string>
.)
OTHER TIPS
That correct, fputs
does not understand how a std::vector
is laid out in memory.
You should actually have got a compile error when you tried to pass a std::vector
to fputs()
. Did you try to work around the error by adding a cast or something?