C while循环跳过输入

时间:2013-04-29 16:44:22

标签: c input while-loop

这是一个家庭作业问题。我有一个正在读取输入的C程序。它需要用户想要记录的许多人,这里由变量选择指定,然后将他们的名字和姓氏和年龄记录到相应的数组中。我有一个while循环来获取用户的输入,但是第一个循环通过while循环完全跳过获取第一个输入。但是,在第一个循环之后,它会正确记录用户的输入。我想知道我可能做错了什么。这是我的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++;
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

以这种方式修复您的代码

i = 0;
while(i < choice)

while应该停在choice - 1而不是choice,因为来自0的C strat中的数组索引。

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