Filip Laurentiu Filip Laurentiu - 21 days ago 7
C Question

Multiple word in a string 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();
}


Hi guys!
I want to store in a struct a name of a student and his score at a class.
At the first loop, I can store multiple words in the variable "name" but, at the second loop, it jump over.

Answer

First: You need to start your loop with zero (i = 0), because C arrays are zero-based.

That said, I guess your problem is because the last scanf() leaves a line break in the stdin buffer. You can try the following code:

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

Note: There's a builtin function (fflush()) to flush the input buffer, but sometimes, for some reason it does not work, so we use the custom clean_stdin() function.

Comments