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
What is the common error occurred while using scanf() statement in C language?
Problem
Common error occurred while reading string and numeric data using scanf() function in C language
Solution
The scanf() function is used to read formatted input from stdin in C language. It returns the whole number of characters written in it otherwise, returns a negative value.
Generally in case of scanf() function while reading string values after integer from the user, we get frequent errors.
Example
Following is a C program which reads roll number (integer value) and name of a student −
#include <stdio.h>
struct student {
char name[10];
int roll;
} s;
int main(){
printf("Enter information of students:
");
printf("\nEnter roll number: ");
scanf("%d", &s.roll);
printf("\nEnter name: ");
gets(s.name);
printf("\nDisplaying Information of students:
");
printf("\nRoll number: %d\t", s.roll);
printf("\nname:%s\t", s.name);
return 0;
}
Output
In the above example, roll no: was read by the compiler, After that compiler is not able to read name and moves to next statement which was printf("Roll Number is: %d\t, s.roll);
and the output is "Roll number: 3 name: "
This is the common error occurred while reading string and numeric data using scanf() function in C language.
Enter information of students: Enter roll number: 3 Enter name: //error Displaying Information of students: Roll number: 3 name: //error
