0

I am trying to read from a file which has the content

Mohan 
Singh

And write it into another file. The code I am using is the following

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Create a text string, which is used to output the text file
    string myText;

    // Read from the text file
    ifstream MyReadFile("demo.txt");

    FILE *f1;
    f1 = fopen("demo_out.txt","w+");

    // Use a while loop together with the getline() function to read the file line by line
    while (getline (MyReadFile, myText)) {
        fprintf(f1, "%s\n", myText);
    }

    fclose(f1);

    // Close the file
    MyReadFile.close();
}

But it is storing some gibberish output in the file. Where am I going wrong?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Turing101
  • 347
  • 3
  • 15
  • `fprintf(f1, "%s\n",myText);` The `%s` format specifier expects a C string as an argument, but you pass a `string` instead. To fix it, lookup [`c_str()`](https://en.cppreference.com/w/cpp/string/basic_string/c_str). And if you don't get a compiler warning on that line of code then turn the warning level up. – dxiv Mar 14 '21 at 06:45
  • 2
    [Warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – n. m. could be an AI Mar 14 '21 at 06:49

0 Answers0