
Hi there! At first glance, your code appears to make intuitive sense. But thanks to the way C programming functions internally, you've ended up with several problems in your code.
The two major issues are:
1. Using \n with scanf
Here's how you've taken input for age:
scanf("%d\n", &enployee1.age);Please don't do this. In scanf format strings, whitespace characters (including \n) mean: consume any amount of whitespace, then keep waiting until the next non-whitespace character appears.
So scanf("%d\n", ...) will:
read the integer,
then consume the newline you typed,
and then block until you type the first non-whitespace character of the next input (for example, the first letter of the name).
To fix this, please remove \n from this code like this:
scanf("%d", &enployee1.age);Then consume the leftover newline before reading a line of text:
getchar(); Here, getchar() will consume the newline character \n entered after the age input so it doesn't interfere with the next input statement.
2. Getting individual character input for "name" and printing the individual characters instead of printing the name as a single string.
On the surface, it makes sense to use a loop to get individual character inputs for a string (since scanf() can only take input for a single word).
But there are many problems with this:
Using a loop from 0 to 49 means the code will always take input for 50 characters, even if the actual name contains far less characters (say, 20 characters). This is wasteful.
This loop also doesn't add a null terminating character
\0at the end of the string.Printing each character of the string is not ideal. It's better to print the entire name as a string rather than individual characters.
To fix this, please use fgets() to get string input like this:
fgets(employee1.name, sizeof(employee1.name), stdin);A Minor Spelling Mistake
You've misspelled Employee by writing it as Enployee, and your object names also have this mistake.
This doesn't matter within the code but it's still better to use proper spellings.
Full Solution
#include
// create Person struct
struct Employee {
int age;
char name[50];
};
int main() {
// create struct variable
struct Employee employee1;
// get age input for employee1's age
scanf("%d", &employee1.age);
// use getchar() to consume the newline
getchar();
// get name input for employee1's name
fgets(employee1.name, sizeof(employee1.name), stdin);
// print name and age
printf("%s", employee1.name);
printf("%d", employee1.age);
return 0;
} Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer