0

Why isn't the getline() method not working in the second iteration of the first while loop? It is printing "Enter consumer id" but it does not wait for the input, it goes to next while loop asking "Enter consumer name". This program is meant to input details of different consumers and display the details until the user enters -1 to exit. I'm able to enter all the details of the 1st consumer but in the next iteration i cant enter the consumer id, it just prints enter consumer id and goes to next loop.


#include <fstream>

using namespace std;

// Driver Code
int main()
{
    // Creation of ofstream class object
    ofstream fout;

    string line;

    int a=0;

    // by default ios::out mode, automatically deletes
    // the content of file. To append the content, open in ios:app
    // fout.open("sample.txt", ios::app)
    fout.open("sample.txt");

    // Execute a loop If file successfully opened
    while (fout) {
        cout<<"Enter consumer id"<<endl;

        getline(cin, line);

        if (line == "-1")
            break;

        fout << line << endl;
            while (fout) {
        cout<<"Enter consumer Name"<<endl;

        getline(cin, line);

        if (line == "-1")
            break;

        fout << line << endl;
            while (fout) {
        cout<<"Enter consumed units"<<endl;
        cin>>a;

        fout << a << endl;
        if(a < 100){
            fout<<"unit charge is "<< (5 * a);

        }
        else if(a>100 && a<200){
            fout<<"unit charge is "<< (10 * a);
        }
        else{
            fout<<"unit charge is "<<( 25 * a);
        }
        break;

    }
    break;
    }

    }

    // Close the File
    fout.close();

    // Creation of ifstream class object to read the file
    ifstream fin;

    // by default open mode = ios::in mode
    fin.open("sample.txt");

    // Execute a loop until EOF (End of File)
    while (fin) {

        // Read a Line from File
        getline(fin, line);

        // Print line in Console
        cout << line << endl;
    }

    // Close the file
    fin.close();

    return 0;
}

Cosmos396
  • 13
  • 3

0 Answers0