N
N
nkorobkov2016-06-05 22:08:45
C++ / C#
nkorobkov, 2016-06-05 22:08:45

Why is it impossible to fill the structure in SI?

Task:
Define a structure with three fields, create an array of 7 elements of the type of this structure, fill it and display it on the screen. I ran into a problem: there are 3 fields in the structure: two of them are of type char , one is of type int . When filling fields of type char , I use the fgets() function , when filling an int field, I use the usual scanf() , while after filling the first element of the array of structures, I skip filling the first field of the next element of the array... This is how it looks:
c643c4de47d84004a5a6c2f2908e4888.png
Here is the code for the program itself:

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

struct aeroflot{
    char nazn[20];
    char tip[20];
    int numr;
};
int main(){
    int i;
    struct aeroflot airport[7];
    for( i = 0; i < 7; i++ ){
        printf("Enter #%d flight nazn: ", i);
        fgets(airport[i].nazn, 20, stdin);
        printf("Enter #%d flight tip: ", i);
        fgets(airport[i].tip, 20, stdin);
        printf("Enter #%d flight numr:", i);
        scanf("%d", &airport[i].numr);

        printf("You entered:\n");
        fputs(airport[i].nazn, stdout);
        fputs(airport[i].tip, stdout);
        printf("\n%d", airport[i].numr);
    }

    return 0;
}

Help me understand what the problem is and explain how the int field is filled in such situations ... Maybe you need to use other functions?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mikhail_404, 2016-06-05
@mikhail_404

Try clearing the buffer at the end of the block in a loop:
fflush(stdin)

A
Anton Zhilin, 2016-06-05
@Anton3

Correct 2 lines:

scanf("%d", &airport[i].numr);
// =>
scanf("%d\n", &airport[i].numr);

printf("\n%d", airport[i].numr);
// =>
printf("%d\n", airport[i].numr);

A
abcd0x00, 2016-06-06
@abcd0x00

Use fgets() + sscanf(). Through fgets () you get each line, and through sscanf () you get the necessary values ​​from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question