vendredi 5 avril 2019

The Loop statment inside if statment is skipping the first getline(cin, name). What is my mistake here? [duplicate]

This question already has an answer here:

This is a program that is writing and reading text from and to a text file. The program is working.

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

Aucun commentaire:

Enregistrer un commentaire