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

 Live Demo

#include <stdio.h>
struct student{
   char name[10];
   int roll;
   char temp;
} s;
int main(){
   printf("Enter information of students:
");    printf("
Enter roll number: ");    scanf("%d", &s.roll);    scanf("%c",&s.temp); //read temporary character    printf("
Enter name: ");    gets(s.name);    printf("
Displaying Information of students:
");    printf("
Roll number: %d\t", s.roll);    printf("
name:%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

Updated on: 09-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements