How to expect different data types in scanf ()?

I am developing a chess game in C for practice only. At the beginning of the game, the user can enter 4 things:

  • ROW <whitespace> COL (i.e. 2 2 )
  • 'h' for reference
  • 'q' to exit

How can I use scanf to expect 2 integers or 1 char?

+4
source share
5 answers

It seems like it would be wiser to read the whole line and then decide what it contains. This will not include the use of scanf , as it will consume the stdin content 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 } } 
+6
source

It’s better not to use scanf at all. This usually causes more problems than what it solves.

One possible solution is to use fgets to get the entire string, and then use strcmp to find out if the user has typed "h" or "q". If not, use sscanf to get the row and column.

+5
source

This is just using scanf

 #include <stdio.h> int main() { char c; int row, col; scanf("%c", &c); if (c == 'h') return 0; if (c == 'q') return 0; if (isdigit(c)) { row = c - '0'; scanf("%d", &col); printf("row %d col %d", row, col); } return 0; } 
0
source
 int row, col; char cmd; char *s = NULL; int slen = 0; if (getline(&s, &slen, stdin) != -1) { if (sscanf(s, "%d %d", &row, &col) == 2) { free(s); // use row and col } else if (sscanf(s, "%c", &cmd) == 1) { free(s); // use cmd } else { // error } } 
0
source

PS: those who did not read and did not understand my answer carefully, please respect yourself, DO NOT VOTE FOR BE!

Besides "get the whole line and then use sscanf", read char on char until "\ n" is entered, also the best way. If a program encounters an "h" or "q", it can immediately take the appropriate action, and you will also provide real-time analysis of the input stream for the clouds.

Example:

 #define ROW_IDX 0 #define COL_IDX 1 int c; int buffer[2] = {0,0}; int buff_pos; while( (c = getchar())) { if (c == '\n') { //a line was finished /* row = buffer[ROW_IDX]; col = buffer[COL_IDX]; */ buff_pos = 0; memset(buffer , 0 , sizeof(buffer));//clear the buffer after do sth... } else if (c == 'h') { //help } else if (c == 'q') { //quit } else { //assume the input is valid number, u'd better verify whether input is between '0' and '9' if (c == ' ') { //meet whitespace, switch the buffer from 'row' to 'col' ++buff_pos; } else { buffer[buff_pos%2] *= 10; buffer[buff_pos%2] += c - '0'; } } } 
-2
source

Source: https://habr.com/ru/post/1497935/


All Articles