C while循环跳过输入

问题描述:

这是一个家庭作业问题。我有一个C程序,它正在输入中读取。它需要用户想要记录的许多人,在这里由变量选项指定,然后将他们的姓名和年龄记录到各自的阵列中。我有一个while循环来获取来自用户的输入,但通过while循环的第一个循环完全跳过了第一个输入。但是,在第一次循环之后,它会正确记录用户的输入。我想知道我可能会做错什么。这是我的while循环:C while循环跳过输入

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++; 
} 

任何帮助将不胜感激。

+0

年龄是int?不要使用fgets – BLUEPIXY 2013-04-29 16:49:50

+0

希望你''''和'选择'声明没问题,代码在'gcc'这里工作。我似乎没有在您的计算机上复制您的问题。另外,不要使用'fgets()'作为'int'。 – 2013-04-29 16:51:41

+0

我被初始化为0,并将选择作为用户的输入。这是我对那些人的:int choice; int i = 0; fputs(“你想添加多少人?”,stdout); 012fscanf(“%d”,&choice); fflush(stdout); – Mouse 2013-04-29 18:00:13

修正你的代码以这种方式

i = 0; 
while(i < choice) 

的同时,应在choice - 1,而不是因为在C STRAT数组索引从0停在choice

0,1,2,...,(choice-1) //==> the total is (choice) indices 
+0

OP的代码读取除第一个以外的所有循环。他可能已经以某种方式宣布了“选择”。他的问题是为什么第一次迭代似乎跳过了。 – 2013-04-29 16:54:37