0

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.

  • 1
    What are the types of `a` and `b`? – Chad Nov 19 '15 at 20:13
  • Possible duplicate of [Why do I get an infinite loop if I enter a letter rather than a number?](http://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number) – Galik Nov 19 '15 at 20:17
  • You do not test the stream state after input. Have a final `ìf(cin)` before processing the data. –  Nov 19 '15 at 20:19
  • It doesn't get stuck in a loop, it is waiting for the second input before proceeding. – Algirdas Preidžius Nov 19 '15 at 20:20

2 Answers2

2

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

cin >> a;
if(a == "end")
  break;
cin >> b;
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
0

To get out of the loop, use

if (a == "end" || b == "end") break; 
PC Luddite
  • 5,883
  • 6
  • 23
  • 39
Nandu
  • 808
  • 7
  • 10