xcode - C language, what is wrong with this? -
this question has answer here:
- how scanf single char in c 8 answers
i wanted make program can read right answers, check students answers comparing right answers , show points of each. problem every time insert first answer program skips second 1 , jumps third. here's how turns out every time:
"insert answer 1: a
insert answer 2: insert answer 3:"
and here's code:
#include <stdio.h> int main() { char v[30], a[30][20]; int i,j,c; (i=0; i<30; i++) { printf("insert answer %d: ", i+1); scanf("%c", &v[i]); } for(j=0; j<20; j++) { printf("student %d\n", j+1); (i=0; i<30; i++) { printf("insert answer %d: ", i+1); scanf("%c", &a[i][j]); } } for(j=0; j<20; j++) { c=0; printf("student %d\n", j+1); (i=0; i<30; i++) { if (v[i] == a[i][j]) c=c+1; } printf("points: %d\n", c); } return 0; }
scanf( "%c", &var );
reads 1 character stdin
. first scanf
reads character , second scanf
reads newline \n
. solve problem, use
scanf( " %c", &var ); ^----- note space
putting space before %c
tells scanf
skip whitespace (including newlines) before reading character.
Comments
Post a Comment