Home > Mobile >  I am trying to input three characters using scanf in loop and also outside loop in C but none is wor
I am trying to input three characters using scanf in loop and also outside loop in C but none is wor

Time:12-05

Here, I am inputting characters using scanf in for loop but it it takes only one character. This problem is not happening with integer. Why?

(1) IN LOOP :-

#include <stdio.h>

int main(void) {
    char p1, p2, p3, c1, c2;
    int i, t;
    // t is the number of testcases.
    printf("Enter number of testcases : ");
    scanf("%d", &t);
    for(i = 0; i < t; i  ){
        printf("Enter three characters : \n");
        scanf("%c%c%c", &p1, &p2, &p3);
        printf("Again enter characters\n");
        scanf("%c%c", &c1, &c2);
        printf("\nEnd");
    }
    return 0;
}

I am able to input only two characters.

OUTPUT :

Enter number of testcases : 2
Enter three characters : 
a
Again enter characters
s

End
Enter three characters : 
d
f
Again enter characters
g
End

(2) WITHOUT LOOP :-

 #include<stdio.h>
 int main(){
    char p1, p2, p3, c1, c2;
    int i, t;
    printf("Enter three characters : \n");
    scanf("%c%c%c", &p1, &p2, &p3);
    getchar();
    printf("Again enter characters\n");
    scanf("%c%c", &c1, &c2);
    printf("\nEnd");
    return 0;
}

OUTPUT :

Enter three characters : 
a
s
Again enter characters
d

End

CodePudding user response:

Place a space before format specifier in scanf.

    #include<stdio.h>
    int main(void) {
    char p1, p2, p3, c1, c2;
    int i, t;
    // t is the number of testcases.
    printf("Enter number of testcases : ");
    scanf("%d", &t);
    for(i = 0; i < t; i  ){
        printf("Enter three characters : \n");
        scanf(" %c %c %c", &p1, &p2, &p3);
        printf("Again enter characters\n");
        scanf(" %c %c", &c1, &c2);
        printf("\nEnd");
    }
    return 0;
}

CodePudding user response:

What is happening is that scanf is looking for 3 characters in stdin to assign to p1, p2 and p3.

After you enter 'a' and 's', stdin has 4 characters. 'a','\n','s','\n'

So, p1 gets 'a', p2 gets '\n' and p3 gets 's'. getchar() removes '\n'

Then, when you enter 'd', c1 gets 'd' and c2 gets '\n'.

If you want to enter one character at a time, then you'll need to include the new lines in your scanf as well.
Do it like this:

    scanf("%c\n%c\n%c", &p1, &p2, &p3);
    getchar();
  • Related