首页 > 解决方案 > 如何在循环中使用 sscanf 处理错误以从标准输入获取输入?

问题描述

我正在编写一个代码来从键盘(stdin)读取输入并打印它们。标准输入如下所示。

(6, 10) (6, 12) (6, 20) (6, 25) (9, 25) (10,25)

代码如下:

void main()
{
    int key, value;

    char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
    char *pointer;
    int offset;

    printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
    fgets(input, sizeof(input), stdin);
    pointer = input;

    //read the pairs of values one at a time until the last pair
    //                       leave space before and after value and brackets to skip spaces
    while (sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset) == 2) 
    {
        printf("key is %d, value is %d", key, value);
        pointer = pointer + offset
    }
}

我还想改进错误处理的代码。例如,如果用户输入如下:

(6, 10) (6, 12) (6, ABC) (DEF, 25) (9, 25) (10,25)

我尝试在 while 循环完成后添加一个,显然,一旦扫描了最后一对值scanResult,它就不会像 -1 那样工作。scanResult

void main()
{
    int key, value;

    char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
    char *pointer;
    int offset;
    int scanResult;

    printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
    fgets(input, sizeof(input), stdin);
    pointer = input;

    //read the pairs of values one at a time until the last pair
    //                       leave space before and after value and brackets to skip spaces
    while ((scanResult = sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) == 2) 
    {
        printf("key is %d, value is %d", key, value);
        pointer = pointer + offset
    }
    
    if (scanfResult != 2)
    {
        printf("invalid input"); 
    }
return;
}

有人可以让我如何编写错误处理代码吗?

标签: cerror-handlingwhile-loopscanfstdin

解决方案


你可以这样做:

char *end = input + strlen(input);

while ( pointer < end && (2 == sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) )

推荐阅读