Scanning different types of variables

Viewed 92

My assignment is to make a word-hunter game. The user enters the coordinates and the associated word. Coordinates are in the same form as the ones in a chessboard (Ex: D7 combative) I'm scanning this as:

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

The problem is, when the user types exit, the program should terminate but I scan not only for a string but also for a character, an integer and then for a string. How can I make the program terminate when the input is exit?

1 Answers

You can first scanf the input as a string, then check if its the "exit" string and exit if it is. If not then with sscanf you can get the desired varaibles.

Example

#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;
}
Related