【问题标题】:scanf in while loop only works on first iterationwhile 循环中的 scanf 仅适用于第一次迭代
【发布时间】:2015-03-13 00:31:20
【问题描述】:

我正在编写一个程序来分析我正在编写的模拟器留下的内存转储。您可以输入内存地址和要查看的值的大小,以查看内存转储的内容。

我的代码在 while 循环中运行,但它只能正常运行一次。输入要查看的第二个内存地址时,会打印出我输入了无效的数据类型,而实际上输入的格式正确。

uint32_t address = 0;
char read_size = 0;

    printf("%% ");
    scanf("%c %x", &read_size, &address);

    while(read_size != 'q')
    {
        emu_error = 0;

        switch(read_size)
        {
            case 'q':
                goto end;
                break;
            case 'b':
            {
                BYTE b = get_byte_at_ram_address(ram, address);

                if(emu_error != 0)
                    printf("Error: Unable to retrieve byte from that address.\n");
                else
                    printf("BYTE 0x%x: 0x%x, %d\n", address, b, b);

                break;
            }
            case 'w':
            {
                WORD c = get_word_at_ram_address(ram, address);

                if(emu_error != 0)
                    printf("Error: Unable to retrieve byte from that address.\n");
                else
                    printf("WORD 0x%x: 0x%x, %d\n", address, c, c);

                break;
            }
            case 'd':
            {
                DWORD d = get_dword_at_ram_address(ram, address);

                if(emu_error != 0)
                    printf("Error: Unable to retrieve byte from that address.\n");
                else
                    printf("DWORD 0x%x: 0x%x, %d\n", address, d, d);

                break;
            }
            default:
            {
                printf("Error: Data type unrecognized.\n");
                break;
            }
        }

        printf("%% ");
        scanf("%c %x", &read_size, &address);
    }

    end:

    return 0;

程序输出如下:

Allocated 4096 bytes of RAM.
% d FF
DWORD 0xff: 0x100, 256
% d 103
Error: Data type unrecognized.
% Error: Data type unrecognized.

我做错了什么?

【问题讨论】:

    标签: c while-loop scanf


    【解决方案1】:

    像这样去掉前一个scanf()留下的'\n'

    scanf(" %c %x", &read_size, &address);
    /*     ^ tell scanf to skip white spaces with the %c specifier */
    

    也不要忽略scanf() 的返回值,如果它失败而你没有检测到,它可能会导致非常奇怪的事情。

    【讨论】:

    • 哇。看来scanf 真的很挑剔。感谢您指出了这一点。现在可以使用了
    • @Igor scanf() 其实很痛苦,不如fgets() 稍后再解析输入。成功了吗?
    • scanf() 非常,veryveryvery很难用正确的所有细节。我真的宁愿不教初学者。问题在于,对于某些输入——尤其是那些没有任何格式错误的数据——它非常方便。但这往往会引起麻烦。 sscanf()(经常和fgets()一起使用会好很多;至少你有输入并且如果出现问题可以重新扫描它,不像普通的scanf()
    猜你喜欢
    • 2023-04-07
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多