Reputation: 29
This is a homework issue. I have a C program that's reading in input. It takes a number of people the user wants to record, designated here by the variable choice, and then records their first and last names and age into respective arrays. I have a while loop to get input from the user, but the first cycle through the while loop completely skips getting the first piece of input. After the first cycle through, though, it does correctly record the user's input. I was wondering what I might be doing wrong. Here is my while loop:
char firstName[choice][20];
char lastName[choice][20];
int age[choice][3];
while(i < choice + 1)
{
fputs("Enter the first name of the person ", stdout);
fflush(stdout);
fgets(firstName[i], sizeof firstName[i], stdin);
fputs("Enter the last name of the person ", stdout);
fflush(stdout);
fgets(lastName[i], sizeof lastName[i], stdin);
fputs("Enter the age of the person ", stdout);
fflush(stdout);
fgets(age[i], sizeof age[i], stdin);
i++;
}
Any help would be greatly appreciated.
Upvotes: 0
Views: 821
Reputation: 43578
Fix your code in this way
i = 0;
while(i < choice)
The while should stop at the choice - 1
and not at choice
because the array indices in C strat from 0
.
0,1,2,...,(choice-1) //==> the total is (choice) indices
Upvotes: 0