1

This C code is not waiting for student name. It directly prints total student number. But when I comment out the first printf-scanf statement(or enter number of students:), then code is waiting for the user to enter student name.

#include <stdio.h>

int main()
{

 char name[10];
 int count;

 printf("ENTER NUMBER OF STUDENTS:\n");
 scanf("%d", &count);

 printf("ENTER STUDENT NAME:\n");
 scanf("%[^\n]%*c", &name);

 printf("Total_Students: %d\n", count);
 printf("NAME: %s\n", name);
 return (0);
 }
donjuedo
  • 2,475
  • 18
  • 28
TheDev05
  • 198
  • 10

2 Answers2

0

The second scanf is skipped because the newline character is being interpreted from the first scanf.

For instance, if you entered 2 for number of student, what is being entered is 2\n. The first scanf reads the number 2 and leaves the \n in the buffer which is being interpreted by the 2nd scanf.

You can simply add a space in the second scanf to get past this issue

scanf(" %[^\n]%*c", &name);
Jackson
  • 1,213
  • 1
  • 4
  • 14
-1

change the second scanf() argument to %s and it directly makes the last entry as NULL .