扫描不同类型的变量

问题描述 投票:3回答:1

我的任务是制作文字猎人游戏。用户输入坐标和相关的单词。坐标的格式与棋盘上的坐标相同(例如:D7好斗),我将其扫描为:

scanf(" %c%d %s",&ypos,&xpos,word);

问题是,当用户键入exit时,程序应终止,但我不仅扫描字符串,而且扫描字符,整数和字符串。当输入为exit时,如何使程序终止?

c string scanf
1个回答
1
投票

您可以首先将输入作为字符串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;
}
© www.soinside.com 2019 - 2024. All rights reserved.