我的任务是制作一款寻字游戏。用户输入坐标和关联的词。坐标与棋盘中的坐标形式相同(例如:D7 战斗
)我将其扫描为:
scanf(" %c%d %s", &ypos, &xpos, word);
问题是,当用户键入 exit
时,程序应该终止,但我不仅扫描字符串,还扫描字符、整数,然后扫描字符串。当输入为 exit
时,如何使程序终止?
最佳答案
您可以首先scanf
输入作为字符串,然后检查它是否是"exit" 字符串,如果是则退出。如果没有,那么使用 sscanf
您可以获得所需的变量。
例子
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
char x;
int y;
char word[20];
if (1 != scanf("%19[^\n]", str))
return printf("Invalid input\n"), 0;
if (strcmp(str, "exit") == 0)
return printf("Exiting\n"), 0;
if (3 != sscanf(str, "%c%d%s", &x, &y, word))
return printf("Invalid input\n"), 0;
printf("%c%d %s", x, y, word);
return 0;
}
关于c - 扫描不同类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61157785/