scanf in while循环仅适用于第一次迭代

时间:2015-03-13 00:31:21

标签: c while-loop scanf

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

我在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.

我做错了什么?

1 个答案:

答案 0 :(得分:3)

删除上一个'\n'左侧的scanf()

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

也不要忽略scanf()的返回值,它可能会导致非常奇怪的事情,如果它失败并且您无法检测到它。