c++ - My while statement is getting infinite loop? -
#include "stdafx.h" #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; //this program let user input assignment score , see letter grade int main() { int score; cout << "input score: "; //to make while loop int x = 1; while (x == 1) { cin >> score; if (score >= 90){ cout << "\na"; break; } else if (score >= 80) { cout << "\nb"; break; } else if (score >= 70) { cout << "\nc"; break; } else if (score >= 60) { cout << "\nd"; break; } else if (score >= 0) { cout << "\nf"; break; } else cout << "\ninvalid input"; } }
i'm trying write program let user input score assignment , display resulting letter grade. if user input not valid score, prints "invalid input" , should ask user input again. however, when run program , type in invalid value, goes infinite loop of printing "invalid input". why this? in advance.
when user enters invalid input, cin >> score
fails , leaves error flag set on stream.
subsequent read operations don't until clear flag std::basic_ios::clear()
.
furthermore, since read failed, score
has unspecified value (as did not initialise it), , apparently on test runs unspecified value happens not match of continues, never hit break
.
instead of just:
std::cin >> score;
try this:
if (!(cin >> score)) { // if reading int failed, come here cout << "invalid value! try again" << endl; // clear error flag cin.clear(); // restart loop continue; }
you may need ask stream eat newlines in input buffer. if "invalid value!" message twice, on how that.
Comments
Post a Comment