我正在用C开发一款国际象棋游戏,仅仅是为了练习.在游戏开始时,用户可以键入4个内容:
<whitespace>COL(即2 2)我如何使用a scanf期望2个整数或1个字符?
看起来读取整行是最明智的,然后决定它包含什么.这将不包括使用scanf,因为它会消耗内容stdin流.
尝试这样的事情:
char input[128] = {0};
unsigned int row, col;
if(fgets(input, sizeof(input), stdin))
{
if(input[0] == 'h' && input[1] == '\n' && input[2] == '\0')
{
// help
}
else if(input[0] == 'q' && input[1] == '\n' && input[2] == '\0')
{
// quit
}
else if((sscanf(input, "%u %u\n", &row, &col) == 2))
{
// row and column
}
else
{
// error
}
}
Run Code Online (Sandbox Code Playgroud)
最好避免使用它scanf.它通常比它解决的问题更麻烦.
一种可能的解决方案是使用fgets获取整行,然后使用strcmp以查看用户是否键入"h"或"q".如果没有,请使用sscanf获取行和列.