Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write string to .txt file in C++ using FILE

I have string str = "6.5.1"
I want to write str to file .txt, but the result is ��j
Here my code

FILE *outfile = fopen("solution.txt", "w");
string test = "6.5.1";
fprintf(outfile, "%s\n", test);

I use string, FILE because I want to pass the file as an argument, and convert string from another file to method.

How can I fix this problem?
Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

p\s: sorry, tag is c++ not c

>Solution :

You clarified that you needed a c++ solution and required to use FILE *:

#include <cstdio>
#include <string>

int main(void) {
    FILE *outfile = std::fopen("solution.txt", "w");
    std::string test = "6.5.1";
    std::fprintf(outfile, "%s\n", test.c_str());
    std::fclose(outfile);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading