Katherine C.
Katherine C.

Reputation: 3

How to stop an infinite loop due to invalid input C++

So I want to accept two inputs, a string and an int, and when the user enters "end" to exit out of the loop. My problem is when "end" is entered that it gets stuck in a loop, since (I'm assuming) it is expecting two inputs when the user only types in one. I've done some research and found stuff on discarding the input and resetting it with cin.ignore() and cin.clear(), however, these seem to only apply when accepting a single input, where as I'm asking for two separate inputs on one line, and it doesn't seem to work. What my code is doing is basically asking for a list of things (name value), storing it in an array in a class, and is capped at 10 items. So, when "end" in entered, it only needs to exit the while loop. Everything else seems to work fine, i.e. when I enter 10 items it exits the loop and the rest of the code executes like it should. So there just seems to be a problem when typing in 'end'. (p.s. a is a string and b in an int type). The section of code is:

do {

    cout << "Enter the item and value (enter 'end' to stop): ";
    cin >> a >> b;

    items1.set_name(a, i);
    items1.set_price(b, i);

    i++;

}  while ( i < 10 && a != "end" );

This seems like it should be very simple, and I'm sorry if its a stupid question, but I can't figure it out hahah. Thanks in advance for helping me out.

Upvotes: 0

Views: 997

Answers (2)

Nandu
Nandu

Reputation: 808

To get out of the loop, use

if (a == "end" || b == "end") break; 

Upvotes: 0

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

You need to test the value of a BEFORE proceeding to read b; something like this:

cin >> a;
if(a == "end")
  break;
cin >> b;

Upvotes: 2

Related Questions