Search code examples
c++c++11iostream

reading new line from file and writing to another file in C++ using streams. not reading new line


I am reading IO streams in C++ and have following code

int main() {
     
    fstream output_file;
    output_file.open("cout.txt", ios::out);
    fstream input_file;
    input_file.open("cin.txt", ios::in);

    // backup existing stream buffers 
    streambuf* cin_old_streambuf = cin.rdbuf();
    streambuf* cout_old_streambuf = cout.rdbuf();

    // Get output stream buffer of file and redirect to cout
    streambuf* output_file_streambuf = output_file.rdbuf();
    cout.rdbuf(output_file_streambuf);

    // Get input stream buffer of file and redirect to cin
    streambuf* input_file_streambuf = input_file.rdbuf();
    cin.rdbuf(input_file_streambuf);
    

    /* What ever you do with cout will write to file. */
    string line;
    getline(cin, line);
    cout << line;
    getline(cin, line);
    cout << line;
    getline(cin, line);
    cout << line;
    getline(cin, line);
    cout << line;
}

My input file cin.txt

My name is 
ravi
My age is 
45

output file cout.txt is

My name israviMy age is 45

My question is why program is not reading \n in input. My understanding is that getline reads newline. I am expecting output file is similar to input file. Kindly help what change do I have to main


Solution

  • While getline(cin, line); does retrieve the input from your other file line by line, if you want new lines when printing with cout << line; you should still follow the standard of adding either "\n" or endl; at the end of your cout lines.

    The last part of your code should look like this.

    getline(cin, line);
    cout << line << endl;
    getline(cin, line);
    cout << line << endl;
    getline(cin, line);
    cout << line << endl;
    getline(cin, line);
    cout << line << endl;