My code is meant to allow a user to input a number 0-9 and out that number as a string. i.e. 1 = "one". Pressing Ctrl + D exits the code. Here it is for reference:
#include <iostream>
using namespace std;
#include <stdio.h>
int main(){
int num;
while ( !cin.eof() ) {
cin >> num;
switch(num) {
case 0 :
cout << "zero" << endl;
break;
case 1 :
cout << "one" << endl;
break;
case 2 :
cout << "two" << endl;
break;
case 3 :
cout << "three" << endl;
break;
case 4 :
cout << "four" << endl;
break;
case 5 :
cout << "five" << endl;
break;
case 6 :
cout << "six" << endl;
break;
case 7 :
cout << "seven" << endl;
break;
case 8 :
cout << "eight" << endl;
break;
case 9 :
cout << "nine" << endl;
break;
}
}
return 0;
}
When I input the correct integers, the code behaves as it should. If input a double digit integer like 10, the code just ignores it, which is fine. However if I put in a non-int like "i", "f" or "cat" the program spams "zero" repeatedly and Ctrl + D no longer works to end the program.
Why is this happening? Is there a way to set it so inputting non-ints would behave the same way as inputting double digit ints? If not, is there a way to only allow cin to take in integers? Thanks!