1

If you see below code, it asks the user for choice in menu upon entering a number it executes the relevant function. But loop inside if statement is skipping the first getline while outside if statement it is working nice.

int choice;
cout << "Enter the number related to below menu: "<<endl;
cout << "0: Save to the File: " << endl;
cout << "1: Read from file: " << endl;
cout << "2: Quit the program: " << endl;
cin >> choice;

if (choice == 0) {
    for (int i = 1; i < 10; i++) {
        string str = getString(i);

        // writing it on file
        filePutContents("db.txt", str, true);
    }
    //reading from file
    readContent();
}

And my getString function is here

    string getString(int i) {
string name;
string position;
string batingAverage;
string salary;

cout << "Please enter " << i <<" baseball player name: ";
getline(cin, name);


cout << "Please enter " << i << " baseball player position: ";
getline(cin, position);

cout << "Please enter " << i << " baseball player bating Average: ";
getline(cin, batingAverage);

cout << "Please enter " << i << " baseball player Salary: ";
getline(cin, salary);
return " "+ name +" "+ position +" " + batingAverage +" " + salary;}

You can better understand from the following image. https://imgur.com/Fo1sVbz

Note Its my first time so pardon my miskates

Abrar Ahmad
  • 127
  • 2
  • 10
  • 1
    See [this FAQ](https://isocpp.org/wiki/faq/input-output#istreams-remember-bad-state). In short, "Because the numerical extractor leaves non-digits behind in the input buffer." – metal Apr 05 '19 at 17:25
  • Your code will work fine so long as the user doesn't press enter after their choice. You have no code to read that enter press except the call to `getline`. – David Schwartz Apr 05 '19 at 18:00
  • Thanks for your comment. I got the solution here. https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – Abrar Ahmad Apr 06 '19 at 18:08

0 Answers0