Search code examples
cscanffgetsgets

C: Reading an optional input from console


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).


Solution

  • 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.