为什么我的提示第一次重复两次?

时间:2013-11-08 08:25:58

标签: c string while-loop

以下代码应该提示用户输入学生人数和作业数量,然后提示他们输入每个学生的姓名。

当它因某种原因到达循环要求学生姓名时,它会在一行上打印两次提示

Student name: Student name:

有人可以告诉我为什么会这样吗?以及如何解决它?

我已经多次遇到过这个问题,但是在不同的情况下。

#include <stdio.h>
#include <cstring>

void print_array(char str[20][20], int number) {
    int i;
    for (i=0; i < number; i++) {
        printf("%s\n", str[i]);
    }
    printf("---\n");
}

void main() {
    int students, assignments;
    char names[20][20];

    do {
        printf("How many students are there (between 1 and 20)?");
        scanf("%d", &students);
        if (students < 1 || students > 20)
            printf ("Number of students must be between 1 and 20.\n");
    } while (students < 1 || students > 20);

    do {
        printf("How many assignments are there (between 1 and 10)?");
        scanf("%d", &assignments);
        if (assignments < 1 || assignments > 10)
            printf ("Number of assignments must be between 1 and 10.\n");
    } while (assignments < 1 || assignments > 10);

    int i;
    for(i=0; i < students; i++){
        printf("Student name:");
        fgets(names[i], 20, stdin);
    }

    print_array(names, students);
}

1 个答案:

答案 0 :(得分:3)

当您使用scanf从键盘读取时,您需要考虑它读取您从键盘输入的所有内容,包括 ENTER 键。 scanf使用缓冲区,所以当你写“%d”时,它只提取将 ENTER 留在缓冲区中。下次调用scanf时, ENTER 仍在缓冲区中。

而是使用fgets和atoi来读取和转换整数,它更安全,更容易使用。

char buffer[32];
fgets(buffer,sizeof(buffer),stdin);
assignments = atoi(buffer);

e.g。

char buffer[32];
do 
{
  printf("How many students are there (between 1 and 20)?");
  fgets(buffer,sizeof(buffer),stdin);
  students = atoi(buffer);
  if (students < 1 || students > 20)
  {
    printf ("Number of students must be between 1 and 20.\n");
  }
} while (students < 1 || students > 20);

或更好地执行功能

int getInt()
{
  char buffer[32];
  fgets(buffer,sizeof(buffer),stdin);
  return atoi(buffer);
}

...

do 
{
  printf("How many students are there (between 1 and 20)?");
  students = getInt();
  if (students < 1 || students > 20)
  {
    printf ("Number of students must be between 1 and 20.\n");
  }
} while (students < 1 || students > 20);