Computer >> Computer tutorials >  >> Programming >> C programming

Why is the compiler not reading string after integer in C programming?


Problem

Compiler not reading the string after integer in C programming? How can we solve this problem?

Solution

When you enter an integer number and press enter to read next value, compiler stores null into the string’s first char and string input terminates. Because scanf will terminate whenever it reads a null character.

How to Solve It?

When we are trying to read string or character after int or float, we should read a temporary char which is present in the input buffer.

The following is the program without errors −

Example

#include <stdio.h>
struct student{
   char name[10];
   int roll;
   char temp;
} s;
int main(){
   printf("Enter information of students:\n");
   printf("\nEnter roll number: ");
   scanf("%d", &s.roll);
   scanf("%c",&s.temp); //read temporary character
   printf("\nEnter name: ");
   gets(s.name);
   printf("\nDisplaying Information of students:\n");
   printf("\nRoll number: %d\t", s.roll);
   printf("\nname:%s\t", s.name);
   return 0;
}

Output

Enter information of students:
Enter roll number: 3
Enter name: tutorialspoint
Displaying Information of students:
Roll number: 29806
name:tutorialspoint