0

The following code is supposed to prompt the user for the number of students and number of assignments and then prompt them to enter the name of each student.

When it reaches the loop to ask for student names for some reason it prints the prompt twice on one line

Student name: Student name:

Could someone please tell me why this happens? And how to fix it?

I have run into this issue several times but in different scenarios.

#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);
}
4

1 回答 1

3

当您使用 scanf 从键盘读取时,您需要考虑到它会读取您从键盘输入的所有内容,包括ENTER键。scanf 与缓冲区一起工作,因此当您编写“%d”时,它只提取留ENTER在缓冲区中的那个。下次调用 scanf 时ENTER仍在缓冲区中。

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

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

例如

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);
于 2013-11-08T08:34:14.623 回答