2

The user may use 2 commands:

move black

(or)

move

So the 'black' part is optional.

I know that the user input is confined to 50 characters top, so I can use scanf() to read each string by itself.

However, I cannot use 3 times scanf() as for the second option - there will be an error (I think ..).

Is there a function that allows me to read and if there's no input it will inform that?

Is gets (or fgets) an appropriate one? (remember thaat the line is no longer than 50 characters).

TryinHard
  • 4,078
  • 3
  • 28
  • 54
din
  • 25
  • 7

3 Answers3

3

Use fgets() to take all the characters as input.

char * fgets ( char * str, int num, FILE * stream );

fgets() reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

For better understanding, follow the program:

#include<stdio.h>
#include<string.h>

int main() {
  char string1[50];
  char string2[50];

  int res;

  printf("String1:\t");
  fgets (string1, 50, stdin); // move black

  printf("String2:\t");
  fgets (string2, 50, stdin);  // move

  res = strcmp(string1, string2); // move black with move

  printf("strcmp(%sstring1,%sstring2) = %d\n",string1,string2,res);
}

Input:

move black

move

Output:

String1: String2: strcmp(move black string1,move string2) = 32

Hope this will help you to solve your problem.

You can run live here.

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
2

Read the entire command from user into a temporary buffer using fgets():

char * fgets ( char * buffer, int num, FILE * stream );

Now, you can tokenize the read input via strtok() function:

char *strtok(char *string, const char *delimterTokens);

Using a strcmp(), check for the comparison with back.

TryinHard
  • 4,078
  • 3
  • 28
  • 54
2

I don't know if I really understand the question, but i'd say that you only need to read the input with a function like scanf/gets/read, and then to cut it using the space.

In order to do so, you could use

char *strtok(char *str, const char *delim) (man page here)

to cut the string that you have read before and then compare the second string with

int strcmp(const char *s1, const char *s2) (man page here)

This way, the user won't have to press enter two times.

I hope it'll help you.

4rzael
  • 679
  • 6
  • 17