Search code examples
c++while-loopcin

Why does these lines of code cause my program to only accept my input after I've entered it twice (pressing enter after each entry)?


I am still kind of new to C++ (currently taking a course) and I am so close to finishing my final project. But these lines of code and other like it within my program causes my program to only accept input after it has been entered twice. I spent 2 hrs retyping it and still no avail.

 cout <<endl<< "Enter balance:"<<endl;
 cin >> balance;
 while(!(cin>>balance))
{
    cin.clear();
    cin.ignore(999,'\n');
    cout<<endl<<"Invalid data type! Number expected. Please enter balance again:"<<endl;
}

Solution

  • Get rid of the double call to read from stdin.

    cout << endl << "Enter balance:" << endl;
    //cin >> balance;
    while(!(cin >> balance)) { //This reads in, and continues while read was NOT successful
        cin.clear();
        cin.ignore(999,'\n');
        cout << endl << "Invalid data type! Number expected. Please enter balance again:" << endl;
    }