I am writing a simple program in C using structs. The user needs to enter some values for the struct - a name and age. After I enter the data for the first time, the second time the program just skips one of the fields and only wants me to enter the second field of the data. I can't figure out what's wrong.
struct Person {
char name[20];
int age;
};
void main(){
struct Person pArray[10];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
scanf("%d", &pArray[i].age);
}
}
As you can see, after entering Jonathan and 45 for the first time, the second time it skipped the name and wants only the age. Why is this happening?
I try not to mix formatted and unformatted input (eg, fgets
and scanf
). Here is your program using only fgets
for input:
#include <stdio.h>
struct Person {
char name[20];
int age;
};
int main(){
struct Person pArray[10];
char numberBuffer[20];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
fgets(numberBuffer, 20, stdin);
sscanf(numberBuffer, "%d", &pArray[i].age);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.