-2
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void trinanguloNumeros(){
    char caracter = 'y';
    int iTamano;

    while (caracter == 'Y' || caracter == 'y') {
        printf("Realizar triangulo:\n");
        printf("De que tamaño desea su triangulo? [1-20]");
        scanf("%i", &iTamano);

        int i,j;
        for(i=1; i<= iTamano; i++ ){
            for(j=1; j <= i; j++){
                printf("%i", j);
            }
            printf("\n");
        }

        printf("Desea Intentar nuevamente? [y/n]\n");
        scanf("%c", &caracter);
        printf("%c", caracter);

    }
    printf("Termina!!");
}

int main(void){
    trinanguloNumeros();
    return 0;
}

The second scanf for the var caracter doesn't works and breaks the while loop. I have no idea why this breaks the loop and the variable is not set again.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
MikeVelazco
  • 885
  • 2
  • 13
  • 30

3 Answers3

5

Put a space in front of %c to prevent scanf from reading the newline left in the buffer by the previous scanf.

scanf(" %c", &caracter);     // see the added space?

This space consumes all whitespace left in the input buffer. In the case of %d and %s formats, it happens automactically, but not with the %c format.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Wow. I was not aware a space would handle it, and was generally doing it with an extra `scanf` (which is an alternative, but this is definitely neater). +1 – aspiring_sarge Jan 17 '16 at 19:11
  • The `newline` might have been left by a previous `%d` format for `int`, in which case your additional `scanf` would have to precede the `char` entry. But if there wasn't one there, your method would fail. – Weather Vane Jan 17 '16 at 19:15
  • Then, after the first ´scanf´, should I put a space before any ´%ANYTHING´ on the next ones? Which could be a better way to make this? – MikeVelazco Jan 17 '16 at 19:23
  • Just put one before the `%c` format. As said in the answer, most formats consume leading whitespace anyway. Note to self: read the manual. – Weather Vane Jan 17 '16 at 19:29
0

That's because \n remains in the buffer. You can fflush(stdin); but I do not advice you to do that because of undefined behaviour. Instead you can put a space before %c, this will do the trick.

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
0

This happens because scanf leaves the new line character in the buffer after reading the first value. Hence the while loop breaks.

 scanf("\n%c", &caracter);

This should fix your problem.

thanosgn
  • 13
  • 3