c - 关于处理scanf无效输入的问题

标签 c scanf

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);
}

当我在终端中运行上面的 scanf 函数时,我希望读取并接受两个字符。例如,“AB”将是有效的终端输入。但在这种情况下,我希望我的代码能够检测无效输入(例如“ABC”)并相应地通知用户。上面的以下代码不适用于有效和无效输入,但我不知道为什么。任何见解将不胜感激。此外,我如何能够检测其他类型的无效输入,例如“A”或“”,并能够相应地通知用户?

最佳答案

使用fgets进行输入。根据需要进行解析。 sscanf 只是解析的一种选择。
这使用 A 到 I 作为有效行,使用 1 到 9 作为有效列。可以根据实际需要进行更改。
如果使用 fgets 进行输入,则对所有输入都使用 fgets。不要与 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;
}

关于c - 关于处理scanf无效输入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534668/

相关文章:

c: ls -l 实现给出了未定义的行为

c - 使用数字配方的 C 随机数

c - 从c文件中读取整数值

c - printf/scanf 的输入/输出选项

c - 使用 sscanf 时区分换行和错误

检查用户是否输入了 int - C

c - Makefile 不会在 header 修改时重建对象

c - 自动将一个套接字转发到另一个套接字

c - 为什么一个内核执行的指令多于它所占的指令份额?

c - 使用 scanf 为结构赋值后程序停止