#include <iostream>
usingnamespace std;
int main () {
int n;
do {
cout << "Enter number of players: ";
cin >> n; //replaced with scanf("%d", n)
if (n > 0 && n <= 5) break;
else cout << "Value unexpected!";
} while (1);
cout << n;
cin.get();
return 0;
}
If n is bigger than 0, equal or less than 5 and also an integer, the program will print n. (If user enter some character, n will be some big number like 12340 so I can easily check if n is an integer or not).
If I enter a string, the loop will repeat of course but it will never ask user for input at line 9: cin >> n (scanf will, too). That's my problem.
(If user enter some character, n will be some big number like 12340 so I can easily check if n is an integer or not).
That isn't a very good approach for that. I would suggest something like
1 2 3 4 5 6
while(std::cout << "Please enter an integer: " && !(std::cin >> n)) //inputs and fails
{
std::cin.clear():
std::cin.ignore(1024, '\n'); //1024 can be a large number of std::numeric_limits<std::streamsize>::max()
std::cerr << "Error - The \"number\" entered was not valid." << std::endl;
}
The problem is that you have your input stream in a failed state then you try to read and it doesn't know what to do.
I would also suggest checking to make sure that the next character is a newline.
1 2 3 4
char c;
//read in number
std::cin.get(c);
//if c == '\n it is good otherwise failed.
Another approach would be to read into a string with std::getline then use a stringstream and make sure it is the correct format.
#include <iostream>
#include <string>
#include <sstream>
void Check(int& n) {
std::string s;
std::cout << "Enter a number: ";
std::cin >> s;
std::cout << "Input: '" << s << "'\n"; // Pressed Enter with empty input, would not print
if (s == "\n" || !(std::stringstream(s) >> n)) // s == "", s == "\0" not gonna work
{
std::cout << "Input is invalid\n";
Check(n);
}
}
int main () {
int n;
Check(n);
std::cout << n;
System::Console::ReadLine();
return 0;
}