Home > Software design >  What is the use of scanf("\n"); statement before scanf("%[^\n]%*c", s)?
What is the use of scanf("\n"); statement before scanf("%[^\n]%*c", s)?

Time:09-20

What is the use of scanf("\n"); statement before scanf("%[^\n]%*c", s) ?

int main() 
{
    char ch;
    char str [100];
    char s[100];
    scanf("%c",&ch);
    printf("%c",ch);
    scanf("%s",&str);
    printf("\n%s",str);
    scanf("\n");            // <<< what is the purpose of this line
    scanf("%[^\n]%*c",s);
    printf("\n%s",s);
    return 0;
}

So what is the use of scanf("\n"); statement before scanf("%[^\n]%*c", s) ?

CodePudding user response:

After this incorrect call of scanf

scanf("%s",&str);

where the second parameter shall be

scanf("%s",str);

the input buffer can contain the new line character '\n' and the next call of scanf

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

can read as a result an empty string.

So this call

scanf("\n");

is an attempt to remove the new line character from the input buffer.

However it will be better just to write

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

See the leading space in the format string. It allows to skip white space characters in the input buffer.

CodePudding user response:

What is the use of scanf("\n");

The true answer is probably that the original author of this code was flailing, desperately trying to get scanf to work, despite scanf's various foibles.

Other evidence that the original author was having problems:

scanf("%c", &ch);

When reading individual characters, the %c often does not work as expected or as desired. Most of the time, at least in code like this, it is necessary to add a space, like this: " %c".

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

This line, also, is difficult to understand. It is attempting to read one full line of text, a task which scanf is not well-suited for.

Overall the code appears to be attempting to read one single character, followed by one string (not containing whitespace), followed by one full line of text (possibly containing whitespace).

Given its shortcomings (and scanf's shortcomings), I'd say it's not even worth trying to figure out what the original code will do. A considerably cleaner way of accomplishing this task (still using scanf) would be

if(scanf(" %c", &ch) != 1) exit(1);
printf("%c\n",ch);
if(scanf("           
  • Related