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; }
}