简体   繁体   中英

C++ - After running while loop with cin, the program won't take input again

I am running a while loop that will take floats entered by users and add them together until something else is put in the input.

while(cin >> input)
{
    price += input;
    cout << "Next price: ";
}

After this, I have the user input how much they paid:

cout << "Enter the amount paid: ";
cin >> paid;
cout << "You paid: " << paid << endl;

When running the program, the loop executes fine, and I can get it to cout the total price correctly, but it skips the cin >> paid; line and will output as You paid: nan .

I tried putting cin.clear() between the loop and the next input, but then upon running it, the output was: You paid: 0

Do I need to change my while loop or use a different version to clear input? I'm pretty new to C++. Thanks!

When you use cin.clear() , it resets the error flags. However, the data in the stream are still there. You'll need to ignore the rest of the line before trying to read paid .

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Make sure to add #include <limits> to use std::numeric_limits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM