0

Im doing a struct to register students´ info, previously I asked the user how many he wanted to register and proceeded to do it with a for loop:

case 1:
printf("How many students you want to register?:(no more than 10) \n");
scanf("%d", &num);
fflush(stdin);
printf("\n");
for(int i=0;i<num;i++){
   alumno[i]=llenarInfo(alumno[i]);
}
printf("---------------------\n");

but how can I do it 1 at a time? I tried increasing i after the loop for but if I register 2 or more and want to print them all it only prints the last one and when asking for the name of the student (atm of filling the info) it automatically jumps to the next member of the struct:

struct Usuario llenarInfo(struct Usuario alumno){

    printf("Dame el nombre: ");
    gets(alumno.nombre);
    fflush(stdin);
    printf("");

jumps this^^

    printf("Dame el codigo de alumno: ");
    scanf("%d", alumno.codigo);
    fflush(stdin);
    printf("");
    printf("Dame el email: ");
    scanf("%s", alumno.email);
    fflush(stdin);
    printf("");
    printf("Que carrera estudia?: ");
    scanf("%s", alumno.carrera);
    fflush(stdin);
    printf("");
    printf("Cual es el sexo? H Hombre- M Mujer: ");
    scanf("%s", alumno.sexo);
    fflush(stdin);
    printf("");
    printf("Cual es la edad?: ");
    scanf("%s", alumno.edad);
    fflush(stdin);
    printf("\n");

return alumno;
flaviodesousa
  • 7,255
  • 4
  • 28
  • 34
Saul
  • 1
  • 1
  • Loop over the elements in your array and check for equality using `strcmp() == 0` for string members. See [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) – David C. Rankin May 26 '20 at 02:12
  • Also see [fflush(stdin) does not work](https://stackoverflow.com/questions/20081062/fflushstdin-does-not-work-compiled-with-gcc-in-cygwin-but-does-compiled-with-v) – user3386109 May 26 '20 at 02:18
  • (well -- unless using VS that provides a non-standard implementation....) – David C. Rankin May 26 '20 at 02:27
  • Evidently OP is not using VS. Hence the "jumps this^^" comment. – user3386109 May 26 '20 at 03:21
  • just do a function that reads a string using fgets and removes the trialing \n that you get with fgets – AndersK May 26 '20 at 04:21

1 Answers1

0

but how can i do it 1 at a time?

from your question I think the fflush is not working you can define a simple flush function to use it instead

void _flush() {
  int c;
  while((c = fgetc(stdin)) != EOF) {
    if(c == '\n') break;
  }
}

besides you should use fgets instead of gets, because gets doesn't check for overflows and that makes it dangerous, and it's no more in C standard!

Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18