cprintfscanftrailing-newline

Trailing newline when using scanf() to take string input with whitespace


I am getting problem when using scanf() to take int input, then move to take a whole string that also accept whitespace in it. But somehow the scanf() take place first before the printf() even showed up. Still playing around with either scanf() and fgets() for proper solutions

Here is my snippet code

int age; char name_user[35];
printf("age\t: "); scanf("%d\n",&age);
printf("name\t: "); scanf("%[^\n]%*s", name_user);
printf("result\t: %s is %d years old\n",name_user,age);

with the output like this

age    : 30
hotpotcookie
name   : loremipsum
result : hotpotcookie is 30 years old

are there any workarounds for the input hotpotcookie take place in the name output? so it could be similar like this

age    : 30
name   : hotpotcookie
result : hotpotcookie is 30 years old

Solution

  • "\n" consumes 0 or more white-spaces until a non-white-space is detected. This means scanf() will not return at the end-of-line as it is looking for white-spaces after a '\n'.


    scanf("%d\n",&age); does not return until detecting non-white-space after the numeric input.

    Use scanf("%d",&age);.


    scanf("%[^\n]%*s", name_user); also risks buffer overflow.
    Use a width as in scanf(" %34[^\n]", name_user);


    Better code checks the return value from scanf() before using the object(s) hopefully populated by the scan.


    Even better code does not use scanf(). Instead use fgets() to read a line of user input into a string and then parse with strotl(), sscanf(), etc.