0

I am new to C++ and making a simple code to read/write to a file: when trying to write to file the getline(cin, data) function gets skipped, although all the other commands get executed. Can someone help me figure out what I am missing or doing wrong? Below is my code:

#include <iostream>
#include <string>
#include <fstream> 

using namespace std;



int main()
{
    
    fstream rfile("abc.txt",ios::in | ios::out | ios::app);
    if (rfile.is_open()==true)
    {
        cout << "File is open" << endl;
        int selection;
        cout << "Enter 1 to  write into File" << " || " << "Enter 2 to read File" << endl;
        cin >> selection;
        if(selection ==1)
        {
        cout << "Type text to Enter" << endl;
        cout << "Entering input ......" << endl;
        string data;
        getline(cin, data); //--- gets skipped
        cout << data << endl;
        cout << "Done writing ......." << endl;
        rfile << data;
        }
        else if(selection==2)
        {
            string reading_line;
            while (rfile.good()) 
            {
            getline(rfile, reading_line);
            cout << reading_line << endl;
            }
        }
        else {
            cout << "GOOD BYE" << endl;
        }
        cout << "File closed Successfully" << endl;
        rfile.close();
        
        

    }
    else { cout << "ERROR OPENING FILE" << endl; }
    

    
    
    
}
  • 1
    This is a very common problem that people run into when combining stuff like `cin >> selection;` with `getline`. What happens, is you read an integer from the stream (hopefully), but in the very best case, the newline you typed after that integer still remains in the stream. So the next call to `getline` will read everything after the integer (if anything) up to that newline. It's best not to mix your inputs like this. If input is line-based, then use `getline` for everything, and then read individual stuff (like `selection`) out using `stringstream`. – paddy Oct 29 '21 at 03:02
  • I doubt that the `getline` function call is getting skipped. That function will read the rest of the line that was left over by `cin >> selection;`, which is probably nothing. Therefore, it will probably read an empty string. – Andreas Wenzel Oct 29 '21 at 03:03
  • Thank you paddy and Andreas, your suggestion guided me to the answer: I basically added cin.ignore(); after the cin>>selection to clear the above behavior and it works – user14338135 Oct 29 '21 at 03:25

0 Answers0