0

I'm sorry if this question is stupid, but it's been kind of bugging me. I have written a program that is supposed to accept user input 5 times and then print out the result each time (i am using a while loop.) Here is the code I wrote:

#include <iostream>

int main()
{
    int x = 1;
    int number;

    while (x <= 5)
    {
        std::cin >> number;
        std::cout << number << std::endl;
        x++;
    }

    return 0;
}

However, after compiling and running (i'm using clang) the program only lets me insert user input once and then it just prints a bunch of 0's:

jakdfjaksdfjk
0
0
0
0
0

I am really confused why this behavior happens. Shouldn't you be able to pass in user input 5 times? Why does this behavior happen? Help would really be appreciated.

mochimochi
  • 23
  • 4

2 Answers2

2

You are trying to read an integer and "jakdfjaksdfjk" would be a string, that's why that happens. Type something like 1 4 8 35 42 and it'll work as you expect

  • The actual problem is that the program can't handle invalid input properly. A good program will handle any input, good or bad, and handle accordingly instead of going into an infinite loop. – rustyx Aug 13 '20 at 20:30
0

You should consider checking the validation of std::cin:

#include <iostream>

int main(void) {
    int x = 1;
    int number;

    while (x++ <= 5) {
        std::cin >> number;

        // If the input isn't an integer, the breaks the loop and quit
        if (!std::cin.good()) {
            std::cout << "Numbers only please.\n";
            break;
        }

        // Otherwise, simply print...
        std::cout << number << std::endl;
    }

    return 0;
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34