Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why is the compiler not reading string after integer in C programming?
When reading string input after integer input in C, a common issue occurs where the string appears to be skipped. This happens because scanf() leaves a newline character in the input buffer after reading the integer.
The Problem
When you use scanf() to read an integer and then try to read a string using gets() or fgets(), the leftover newline character from the integer input is immediately consumed by the string function, causing it to terminate without reading actual string input.
Solution Methods
Method 1: Using a Temporary Character
Read the leftover newline character using a temporary variable before reading the string −
#include <stdio.h>
struct student {
char name[50];
int roll;
char temp;
} s;
int main() {
printf("Enter roll number: ");
scanf("%d", &s.roll);
scanf("%c", &s.temp); /* consume leftover newline */
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
printf("\nStudent Information:<br>");
printf("Roll number: %d<br>", s.roll);
printf("Name: %s", s.name);
return 0;
}
Enter roll number: 101 Enter name: TutorialsPoint Student Information: Roll number: 101 Name: TutorialsPoint
Method 2: Using getchar()
Use getchar() to consume the leftover newline character −
#include <stdio.h>
int main() {
int age;
char name[50];
printf("Enter your age: ");
scanf("%d", &age);
getchar(); /* consume leftover newline */
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("\nYou entered:<br>");
printf("Age: %d<br>", age);
printf("Name: %s", name);
return 0;
}
Enter your age: 25 Enter your name: John Smith You entered: Age: 25 Name: John Smith
Method 3: Using scanf() with Space
Add a space before the format specifier to skip whitespace characters −
#include <stdio.h>
int main() {
int num;
char str[50];
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter a string: ");
scanf(" %49[^<br>]", str); /* space before % skips whitespace */
printf("\nResults:<br>");
printf("Number: %d<br>", num);
printf("String: %s<br>", str);
return 0;
}
Enter a number: 42 Enter a string: Hello World Results: Number: 42 String: Hello World
Key Points
-
scanf()leaves the newline character in the input buffer after reading integers. - Always use
fgets()instead of the deprecatedgets()function for safety. - The space before the format specifier in
scanf()tells it to skip any whitespace characters. - Using
getchar()is a clean and simple solution for consuming leftover characters.
Conclusion
The issue of skipped string input after integer input is easily solved by consuming the leftover newline character. The getchar() method is the most commonly used and reliable approach for handling this buffer issue.
