字符串C中的多个单词

时间:2016-11-13 21:47:57

标签: c

#include <stdio.h>
#include <conio.h>

#define STUD 3

struct students {
  char name[30];
  int score;
  int presentNr;
} student[STUD];

void main() {
  for (int i = 1; i <= STUD; i++) {
    printf("Name of the student %d:\n", i);
    scanf("%[^\n]s", student[i].name);

    printf("His score at class: ");
    scanf("%d", &student[i].score);

    printf("Number of presents at class: ");
    scanf("%d", &student[i].presentNr);
  }
  getch();
}
你好! 我想在结构中存储学生的名字和他在课堂上的分数。 在第一个循环中,我可以在变量“name”中存储多个单词,但是在第二个循环中,它会跳过。

1 个答案:

答案 0 :(得分:-1)

首先:您需要以零(i = 0)开始循环,因为C数组从零开始。

那就是说,我猜您的问题是因为最后scanf()stdin缓冲区中留下换行符。您可以尝试以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STUD 3

struct students {
  char name[30];
  int score;
  int presentNr;
} student[STUD];

void clean_stdin(void)
{
  char c;
  do c = getchar(); while (c != '\n' && c != EOF);
}

int main() {
  for (int i = 0; i < STUD; i++) {

    printf("Name of the student %d:\n", i + 1);
    fgets((char*)&student[i].name, 30, stdin);

    // Remove the line break at the end of the name
    student[i].name[strlen((char*)&student[i].name) - 1] = '\0';

    printf("His score at class: ");
    scanf("%d", &student[i].score);

    printf("Number of presents at class: ");
    scanf("%d", &student[i].presentNr);

    // cleans stdin buffer
    clean_stdin();
  }

  getchar();
}

注意:有一个内置函数(fflush())来刷新输入缓冲区,但有时,由于某些原因它不起作用,所以我们使用自定义clean_stdin()函数。