c - 如何在c中验证用户输入?

标签 c

我想知道你如何在c中验证用户输入,我需要用户输入坐标,一个(1-8)中的整数,由(1-8)中的另一个整数分隔,例如“1,1” 。我想知道我是否可以使用 strtok() 或 strtol() 来做到这一点?

最佳答案

如果输入格式固定,使用fgets()获取一行输入然后sscanf()解析输入比使用fgets()解析输入要简单得多使用 strtok()strtol()

以下示例验证用户输入 [1, 8] 范围内的两个整数。如果用户输入的值少于两个,或者值超出范围,或者在接受的值之后有额外的输入,系统会提示用户输入另一对坐标。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char buffer[100];
    int x, y;

    /* sscanf() method: input must be comma-separated, with optional spaces */
    printf("Enter a pair of coordinates (x, y): ");
    if (fgets(buffer, sizeof buffer, stdin) == NULL) {
        perror("Input error");
        exit(EXIT_FAILURE);
    }

    int ret_val;
    char end;
    while ((ret_val = sscanf(buffer, "%d , %d%c", &x, &y, &end)) != 3
           || x < 1
           || x > 8
           || y < 1
           || y > 8
           || end != '\n') {
        printf("Please enter two coordinates (x, y) in the range [1, 8]: ");
        if (fgets(buffer, sizeof buffer, stdin) == NULL) {
            perror("Input error");
            exit(EXIT_FAILURE);
        }
    }

    printf("You entered (%d, %d).\n", x, y);

    return 0;
}

关于c - 如何在c中验证用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45608039/

相关文章:

c - 在 OSX 中从控制台读取输入

c - 修改控制台 C Codeblocks 中先前编写的行

javascript - 在 Node.js 上的服务器内发出子进程

CURL 在发出 http 请求时的奇怪行为(错误 400)

c - 在 C 中,对指针使用 typedef 是一种好形式吗?

c - 我在 C++ 中使用 widestring 时程序崩溃

c - 如何使用 epoll 管理从多个客户端接收多个缓冲区?

c - C程序中的段错误,malloc调用

c - 结构定义(不是实例化)应该放在头文件中吗?

c++ - 非阻塞连接 OpenSSL