Subham Kharel
Subham Kharel

Reputation: 13

For loop not working in c

#include<stdio.h>
#include<conio.h>
int main(){
    char x[9];
    for(i=0; i<=8; i++){
        printf("\nEnter your guess: ");
        scanf("%c", &x[i]);
    }
}

What is wrong with this code? When I enter the value for x[i], the loop runs for two times before letting me enter the value for x[i+1]. Someone please solve this out. I know its a simple error(not sure) but this is bugging the crap out of me.

Upvotes: 0

Views: 123

Answers (1)

Gopi
Gopi

Reputation: 19864

scanf(" %c", &x[i]);

Note the space before %c. This space will make sure the newline character is ignored.

When you enter a character and press enter there is a newline character in the buffer which will be picked up in the next iteration. So you need to ignore it by doing as shown above.

Upvotes: 5

Related Questions