c++ - How do I stop this from infinitely repeating, but still keep the loop? -
on line 33, there break stop code repeating indefinitely, take part in while loop.
the code:
#include <iostream> using namespace std; int main() { while (true){ { cout << "this program counts twos number inputted user." << endl; cout << "input number start counting." << endl; int input; cin >> input; if (!cin.fail())//fails if input not integer { if (input < 0)//makes sure numbers positive { cout << "that not positive number. try again?" << endl; } else if (input % 2 != 0) // makes sure numbers { cout << "that not number. try again?" << endl; } else{ (int = 0; <= input; += 2) //uses loop counting once know number even. { cout << << endl; } } } if (cin.fail())//returns when input other integer. { cout << "that not digit, try again." << endl; break; } } } return 0; } if guys me find why repeats, help.
you need add break statement after loop in order exit loop. without break loop execute , print output , control fall end of while loop start @ top of loop.
i suggest changing if (cin.fail()) else checking if (!cin.fail()). need ignore rest of input , clear error flags if want loop again.
you had set of brackets in while loop. changes code be:
#include <iostream> #include <limits> using namespace std; int main() { while (true) { cout << "this program counts twos number inputted user." << endl; cout << "input number start counting." << endl; int input; cin >> input; if (!cin.fail())//fails if input not integer { if (input < 0)//makes sure numbers positive { cout << "that not positive number. try again?" << endl; } else if (input % 2 != 0) // makes sure numbers { cout << "that not number. try again?" << endl; } else{ (int = 0; <= input; += 2) //uses loop counting once know number even. { cout << << endl; } break; // exit while loop } } else //else when input other integer. { cout << "that not digit, try again." << endl; cin.clear(); // reset error flags cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear input } } return 0; }
Comments
Post a Comment