How do I avoid a string being inputted for an int?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;


int main()
{
string saying="You want some random numbers generated? How many?";
int input;

while(1){

    cout << saying << endl;
    cin >> input;
        if(cin && input>0){
        cout<<"Here ya go, buddy!\n";

            for (int a; input>0 ; input--){
            a=rand();
            cout<< a <<endl;
            }

        saying="Okay, you want more? How many?";
        }
        else {
        cout<<"You trying to be funny?"<< endl;
        saying="";
        }
    }
}


I'm new to programming. I made this simple program to generate n amounts of random numbers. The code messes up badly if someone were to input a string for the variable "input." I thought that setting input to void or a viable integer would fix it in the "else" statement, but that doesn't seem to work. I'm not sure what's going on, it appears to loop the entire while statement without asking for input, so how do I fix this?

Also, any suggestions on cleaning up the code in general would be nice, thanks!
Nevermind, got it to work, but I really don't understand what's going on in that code.

Why does myStream not have to be defined?
Last edited on
It is defined on line 24.
Topic archived. No new replies allowed.