Link to home
Start Free TrialLog in
Avatar of jmsloan
jmsloan

asked on

Append a string to a file

Hello I am trying to create a string variable and append that variable on another line of an open file.

Here is what I have so far

     strftime(var, 30, "%m%d", tm_data);
     string tmpfilename(var);
     journalfile = "C:\\hlmkejrnl\\" + tmpfilename + ".txt";

     // open file with a MMDDhhmmss.txt format to save transaction
        ofstream outfile (journalfile.c_str(), ios::app);

         string ejrnlfile = "Hope this works";
          outfile.write(ejrnlfile);
          outfile.close();

"Hope this works" should append to the file MMDD.txt file, but I get an error

Cannot convert 'string' to 'const char *' in function main()

and

Type mismatch in parameter 's' (wanted 'const char *', got 'string') in function main()

Maybe there would be a better way to open a file and append a string to it?  

Any suggestions?

Thanks,

jmsloan
Avatar of jmsloan
jmsloan

ASKER

I believe I figured it out.  I did this and it seems to work

     strftime(var, 30, "%m%d", tm_data);
     string tmpfilename(var);
     journalfile = "C:\\hlmkejrnl\\" + tmpfilename + ".txt";

     // open file with a MMDDhhmmss.txt format to save transaction
        ofstream outfile (journalfile.c_str(), ios::app);

         string ejrnlfile = "Hope this works\n";
         outfile << ejrnlfile;
         outfile.close();
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Axter and jmsloan are absolutely right, but for the record if you do want a pointer to a char* for a legacy C function, you should copy the std::string into std::vector<char> and '\0'-terminate it.

e.g.
--------8<--------
#include <cstdio> // For yucky old printf
#include <string>
#include <vector>

int main()
{
      std::string str = "Hello world";

      std::vector<char> v(str.begin(),str.end());
      v.push_back('\0'); // C strings need '\0' termination

      std::printf("C programmers like to say \"%s\"",&v[0]);
}
--------8<--------