1

I wanted to make a program that can read the right answers, check the students answers comparing with the right answers and then show the points of each. The problem is that every time that I insert the first answer the program skips the second one and jumps to the third. Here's how it turns out every time:

"Insert the answer 1: a

Insert the answer 2: Insert the answer 3:"

And here's my code:

#include <stdio.h>

int main()
{
    char v[30], a[30][20];
    int i,j,c;

    for (i=0; i<30; i++)
    {
        printf("Insert the answer %d: ", i+1);
        scanf("%c", &v[i]);
    }

    for(j=0; j<20; j++)
    {
        printf("Student %d\n", j+1);

        for (i=0; i<30; i++)
        {
            printf("Insert your answer %d: ", i+1);
            scanf("%c", &a[i][j]);
        }
    }

    for(j=0; j<20; j++)
    {
        c=0;
        printf("Student %d\n", j+1);

        for (i=0; i<30; i++)
        {
            if (v[i] == a[i][j])
                c=c+1;
        }

        printf("Points: %d\n", c);
     }

    return 0;
}
Josh
  • 13
  • 2

2 Answers2

2

The problem is that scanf() leaves a \n in the buffer, so the second call reads that, and then the third call gets the buffer empty and waits for input.

You can clean the buffer yourself with this

void cleanBuffer(){
    while(getchar() != '\n');
}

or stop using scanf() and use fgets() instead and get the data using sscanf(), there are a few reasons why you'd wanna do the latter.

Alex Díaz
  • 2,303
  • 15
  • 24
1

scanf( "%c", &var ); reads exactly one character from stdin. So the first scanf reads a character and the second scanf reads the newline \n. To solve the problem, use

scanf( " %c", &var );
        ^----- note the space

Putting a space before the %c tells scanf to skip whitespace (including newlines) before reading a character.

user3386109
  • 34,287
  • 7
  • 49
  • 68