Aquí, estoy ingresando caracteres usando scanf en for loop pero solo toma un carácter. Este problema no está ocurriendo con enteros. ¿Por qué?
(1) EN BUCLE: -
#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; }Solo puedo ingresar dos caracteres.
PRODUCCIÓN :
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) SIN BUCLE :-
#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; }PRODUCCIÓN :
Enter three characters : a s Again enter characters d EndColoque un espacio antes del especificador de formato en 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; }Lo que sucede es que scanf está buscando 3 caracteres en stdin para asignarlos a p1, p2 y p3.
Después de ingresar 'a' y 's', stdin tiene 4 caracteres. 'a','\n','s','\n'
Entonces, p1 obtiene 'a', p2 obtiene '\n' y p3 obtiene 's'. getchar() elimina '\n'
Luego, cuando ingresa 'd', c1 obtiene 'd' y c2 obtiene '\n'.
Si desea ingresar un carácter a la vez, también deberá incluir las nuevas líneas en su scanf.
Hazlo asi:
scanf("%c\n%c\n%c", &p1, &p2, &p3); getchar();Simplemente coloque un espacio antes de %c en scanf.