Question about dealing with invalid inputs of scan

2020-05-08 07:48发布

void placeg(game** g){
  //place marble;
  char row, col;
  char* buffer = NULL;
  printf("Please enter a move: ");
  scanf(" %c%c%s", &row, &col, buffer);
  // scanf(" %s", buffer);
  pos p = make_pos(charToInt((int)row),charToInt((int)col));
  place_marble((*g),p);
  board_show((*g)->b);
}

When I run the scanf function above in terminal, I expect to read and take in two char. For example, "AB" would be a valid terminal input. But in this case, I want my code to be able to detect invalid inputs such as "ABC" and inform the user accordingly. The following code above does not work for both valid and invalid inputs but I do not know why. Any insights would be greatly appreciated. In addition how would I potentially be able to detect other kinds of invalid inputs such as "A" or "" and be able to inform user accordingly?

标签: c scanf
1条回答
爷的心禁止访问
2楼-- · 2020-05-08 08:39

Use fgets for input. Parse as needed. sscanf is but one option for parsing.
This uses A through I for valid row and 1 through 9 for valid column. That can be changed for actual requirements.
If fgets is used for input, use fgets for all input. Don't mix with scanf.

#include <stdio.h>

int main ( void) {
    char input[128] = "";
    char row = 0;
    char col = 0;
    char nl = 0;
    int result = 0;

    do {
        printf ( "Enter row and col\n");
        if ( fgets ( input, sizeof input, stdin)) {
            if ( 3 == ( result = sscanf ( input, "%c%c%c", &row, &col, &nl))) {
                if ( '\n' != nl) {//not a newline
                    result = 0;
                }
                if ( row < 'A' || 'I' < row) {//A - I valid
                    result = 0;
                }
                if ( col < '1' || '9' < col) {//1 - 9 valid
                    result = 0;
                }
            }
        }
        else {
            fprintf ( stderr, "fgets EOF\n");
            return 0;
        }
    } while ( 3 != result);

    printf ( "row: %c\ncol: %c\n", row, col);

    return 0;
}
查看更多
登录 后发表回答