SivaDotRender
SivaDotRender

Reputation: 1651

last fgets in a loop never executes

I am trying to populate 2 arrays using fgets. For some reason, the last fget of the last loop iteration never executes.

For example, if num_inputs = 5, only 9 lines are read (instead of 10).

int num_imputs;

//read the number of inputs

scanf("%d", &num_imputs);

char secret_arr[num_imputs][8];//stores all the secrets
char encoded_message_arr[num_imputs][256];//stores all the encoded messages

for(int i = 0; i < num_imputs ; i++){

    fgets (secret_arr[i],8, stdin);
    fgets (encoded_message_arr[i],256, stdin);

}

This code works perfectly find if I hardcode num_inputs instead of reading it using scanf(). Can someone explain why this is happening?

Upvotes: 0

Views: 72

Answers (1)

kaylum
kaylum

Reputation: 14044

You are missing a newline in scanf (assuming your input has an ENTER for the num_inputs data entry). Results in the first fgets actually storing an empty string as it stops when it sees the newline that was part of the num_inputs data entry.

Should be:

scanf("%d\n", &num_imputs);

Upvotes: 3

Related Questions