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.

4
  • 5
    jakdfjaksdfjk is not an int, which is the type you're trying to read. Commented Aug 13, 2020 at 18:30
  • 2
    Related/duplicate: How to handle wrong data type input (but I cannot find any question exactly like "why is input skipped") Commented Aug 13, 2020 at 18:33
  • oh... i really overlooked that- Commented Aug 13, 2020 at 18:34
  • Yes it does! Thank you. Commented Aug 13, 2020 at 18:39

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.