Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to input three characters using scanf in loop and also outside loop in C but none is working properly

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading