while 循环中的 scanf 仅适用于第一次迭代
scanf in while loop only works on first iteration
我正在编写一个程序来分析我正在编写的模拟器留下的内存转储。您可以输入内存地址和您希望查看的值的大小,以查看内存转储的内容。
我在 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.
我做错了什么?
像这样去掉前面scanf()
留下的'\n'
scanf(" %c %x", &read_size, &address);
/* ^ tell scanf to skip white spaces with the %c specifier */
也不要忽略 scanf()
的 return 值,它可能会导致非常奇怪的事情,以防它失败而你没有检测到它。
我正在编写一个程序来分析我正在编写的模拟器留下的内存转储。您可以输入内存地址和您希望查看的值的大小,以查看内存转储的内容。
我在 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.
我做错了什么?
像这样去掉前面scanf()
留下的'\n'
scanf(" %c %x", &read_size, &address);
/* ^ tell scanf to skip white spaces with the %c specifier */
也不要忽略 scanf()
的 return 值,它可能会导致非常奇怪的事情,以防它失败而你没有检测到它。