cscanfc-stringsconversion-specifier

Problem while taking multiple inputs in C


I just started learning on C, I was trying to do some exercises. There is an exercise that wants me to take input for a character,a word and a sentence then print it. I tried to take all three input with scanf but when I execute the code program wants the first two inputs but skips the third input and prints the first two. I tried fgets and gets functions too but I couldn't solve the problem.

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

int main() 
{
    char ch;
    char s[100];
    char sen[100];

    scanf("%c", &ch);
    scanf("%s", &s);
    scanf("%[^\n]%*c",sen);
    printf("%c", ch);
    printf("\n%s", s);
    printf("\n%s", sen);
    
    return 0;
}

I tried scanf, fgets and gets to enter all the inputs but I couldn't take and print all of them.


Solution

  • The problem is that this call of scanf

    scanf("%[^\n]%*c",sen);
    

    encounters a new line character '\n' that is stored in the input buffer due to pressing the key Enter in the preceding call of scanf and thus reads an empty string.

    Also in this case

    scanf("%s", &s);
    

    the second argument expression has invalid type char ( * )[100] instead of char *.

    Write instead

    scanf("%c", &ch);
    scanf("%99s", s);
    scanf(" %99[^\n]",sen);
    

    Pay attention to the leading space in the format string in the third call of scanf. It allows to skip white space characters in the input buffer.

    In the first call of scanf you also may place a leading space in the format string

    scanf(" %c", &ch);
    

    It will be useful for example when you read characters in a loop and need to skip the new line character '\n' of a preceding call of scanf.

    As for this call with the conversion specifier s

    scanf("%99s", s);
    

    then the function automatically skips white space characters until a non white space character is encountered. Do placing a leading space in the format string is redundant.