Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expect different data types in scanf()?

Tags:

c

scanf

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?

like image 490
Rodrigo Souza Avatar asked Jan 12 '23 14:01

Rodrigo Souza


1 Answers

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
    }
}
like image 131
Daniel Kamil Kozar Avatar answered Jan 22 '23 11:01

Daniel Kamil Kozar