睿宏 陳
PRO
last month
睿宏country asked

Another question, I changed my code to this one: #include <stdio.h> struct Enployee{ int age; char name[50]; } enployee1; int main(){ scanf("%d\n", &enployee1.age); fgets(enployee1.name, sizeof(enployee1.name), stdin); printf("%s%d", enployee1.name, enployee1.age); return 0; } But why can't I add '\n' in the middle of %s and %d in the printf function?

Udayan Shakya
Expert
last month
Udayan Shakya answered

Hi again! A short answer to this particular question is included in my answer to your previous question.

If you're still confused, you can try the following program and see what happens:

#include 

int main() {

  int age;

  // get age input
  printf("Enter age: ");
  scanf("%d\n", &age);
  
  // print age
  printf("Age: %d", age);

  return 0;
}

You'll see that this program "hangs" after you've entered the age and pressed enter, i.e., it doesn't print the age after you've given the input.

The only way to make it print the age is to give another input and press enter. Here's my full output:

Enter age: 25
a
Age: 25

Notice that I had to enter a (or any other non-whitespace input) to print the age.

Obviously, this is bad because the program appears to be hanging/freezing in the middle of the execution.

And as I've explained in my previous answer, this happens because you're telling scanf() to consume all whitespace characters and wait for non-whitespace character input.

That's what scanf("%d\n", &variable); does, and it's not something you want in your code.

Hope this helps! Let me know if you have any more questions.

C
This question was asked as part of the Learn C Programming course.