How to expect different data types in scanf()?
c, scanf
Solution
Seems like it would be most sensible to read a whole line, and then decide what it contains. This will not include using `scanf`, since it would consume the contents `stdin` stream.
Try something like this :
char input[128] = {0};
unsigned int row, col;
if(fgets(input, sizeof(input), stdin))
{
if(input[0] == 'h' && input[1] == '\n' && input[2] == '\0')
{
// help
}
else if(input[0] == 'q' && input[1] == '\n' && input[2] == '\0')
{
// quit
}
else if((sscanf(input, "%u %u\n", &row, &col) == 2))
{
// row and column
}
else
{
// error
}
}
Problem
I'm developing a chess game in C just for practicing. At the beginning of the game, the user can type 4 things: - ROW`<whitespace>`COL (i.e. `2 2`) - 'h' for help - 'q' to quit How can I use a `scanf` to expect 2 integers or 1 char?