0

I'm trying to solve the following excercise:

Write a C++ program that accepts lines of text from the keyboard and writes each line to a file named text.txt until an empty line is entered. An empty line is a line with no text that’s created by pressing the Enter (or Return) key.

This is what I did:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>   // needed for exit()
using namespace std;


int main()
{
    int control = 1;  // control variable for the while loop
    string line, linein;
    string filename = "text.txt";


    ofstream OutFile;
    OutFile.open(filename.c_str());

    if (OutFile.fail()) // check for successful open
    {
        cout << "\nThe file was not successfully opened"
             << endl;
        exit(1);
    }

// WHILE LOOP THAT ALLOWS ENTERING LINES OF TEXT:
// 
// by entering only the ENTER key the if condition becomes true, the control variable becomes // 0 and the exit from the loop is granted.

    while (control == 1)
    {
        getline(cin, line);
        OutFile << line << endl;

        if (cin.get() == '\n')
        {
            control = 0;
        }
    }



// READ AND DISPLAY THE FILE CONTENTS

        ifstream inFile;
    inFile.open(filename.c_str());
    if (inFile.fail()) // check for successful open
    {
        cout << "\nThe file was not successfully opened"
            << "\n Please check that the file currently exists."
            << endl;
        exit(1);
    }
    
    while (getline(inFile, linein))
        cout << linein << endl;
    inFile.close();


    return 0;
}

However by using the following input:

First Row

Second Row

// ENTER key

This is the output that I get:

First Row

econd Row

The first charachter 'S' of the second line is missing. Why? How can I solve this problem? I'd like to underline that in this case i haven't used the cin.ignore as in most examples that I found on this website. I would be grateful if you could help me in any way since I just started learning C++.

  • To test if `getline()` got an empty input, test against `""` not `\n`. The latter will be removed from the input. – πάντα ῥεῖ Aug 05 '23 at 13:31
  • 2
    What do you think this is doing `cin.get() == '\n'`? That is what is reading the first character of the next line. – john Aug 05 '23 at 14:09
  • 2
    To test for an empty line, test the line, not the input, like this `if (line.empty())` – john Aug 05 '23 at 14:11

0 Answers0