Search code examples
cinputcompiler-constructionscanf

Can someone explain the meaning of this scanf code


I am trying to understand this code for calculating first and follow sets of a grammar. In this scanf has been used with multiple inputs

scanf("%s%c",a[i],&ch);

where a is 2D array and ch is a char. Can someone explain the meaning of this line?


Solution

  • As said in remarks scanf("%s%c",a[i],&ch); try to read a 'word' as a string in a[i] and a char in ch

    Because a 'word' is ended by a separator and there is no space between %s and %c if a character is read to set ch that character is the first separator

    Example :

    #include <stdio.h>
    
    int main()
    {
      char s[10], ch;
      printf("%d\n", scanf("%s%c", s, &ch));
      printf("'%s' '%c' (%d)\n", s, ch, ch);
    }
    

    Compilation and execution:

    pi@raspberrypi:/tmp $ gcc s.c
    pi@raspberrypi:/tmp $ ./a.out
    aze q
    2
    'aze' ' ' (32)
    

    so ch does not get q but the first space after "aze"

    Of course in the case of azeenter

    pi@raspberrypi:/tmp $ ./a.out
    aze
    2
    'aze' '
    ' (10)
    

    ch get newline


    The proper way to not take the risk to write out of the string is to set the max number of characters, in my example above scanf("%9s%c", s, &ch) (9 rather than 10 to have the place for the null character ending the string)

    If the available 'word' has at least 10 characters the 10nth will be get by ch :

    pi@raspberrypi:/tmp $ gcc s.c
    pi@raspberrypi:/tmp $ ./a.out
    1234567890
    2
    '123456789' '0' (48)
    

    Adding a space between %s and %c changes the behavior because the separators are skip between the 'word' and the returned character, example :

    #include <stdio.h>
    
    int main()
    {
      char s[10], ch;
      printf("%d\n", scanf("%9s %c", s, &ch));
      printf("'%s' '%c' (%d)\n", s, ch, ch);
    }
    

    Compilation and execution:

    pi@raspberrypi:/tmp $ gcc s.c
    pi@raspberrypi:/tmp $ ./a.out
    aze    q
    2
    'aze' 'q' (113)
    

    so that time ch gets q