2

I have been learning c++ for about a week now, and I thought I had everything under control, but apparently not. I was mid program, and decided to hit run just to see how things were looking. The program runs, but never ends. I was expecting it to at least print the first cout statement.

#include <iostream>
using namespace std;

int main()
{
    int floors, rooms, i = 0;
    cout << "floors: "; cin >> floors;
    while (floors > i) 
    {
        cout << "rooms: "; cin >> rooms;
        ++i;
    }
}
jooe 15
  • 23
  • 2

1 Answers1

2

You did not "flush your output". Depending upon various settings at various levels of abstraction, the floors: prompt then may not be displayed until there's also more output to go along with it.

Your program, then, is waiting for input before you are visibly prompted for it.

Add << flush to your cout statement to ensure that the text is shown on the screen:

You should also verify that the input to cin was successful, otherwise floors has an indeterminate value and your loop very well may go on "for ever".

cout << "floors: " << flush;
if (!(cin >> floors))
  throw std::runtime_error("Value provided for 'floors' could not be read into an int!");
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 5
    Shouldn't `cin` and `cout` be tied by default, omitting the need for an explicit flush, unless you have explicitly changed the tying in your code? – MicroVirus Jun 30 '16 at 10:18