comparison using characters in c

Asked

Viewed 646 times

2

Okay, the problem is only in function q31 and q311.

http://pastebin.com/8CJwKej4

I left the complete code on the link above.

then here is this function q311:

void q311(){
char forma;
int n,jota,b,i,j;
printf("Informe a figura e o tamanho: ");
scanf("%c",&forma);
scanf("%i",&n);
    if (forma=='q')
    {
        for ( i = 0; i < n; ++i)
        {
        printf("*");
            for ( b = 1; b < n; ++b)
            {
                if ((i==jota)|| (i==0))
                {
                    printf("*");
                }
                else if (b==jota)
                {
                    printf("*");
                }
                else
                    printf(" ");
            }
            printf("\n");
            }
        }
    else if (forma=='t')
    {
        for(int i=n-1;i>=0;i--)
        {
            for(int j=0;j<=i;j++)
            {
             if(i==n-1 || j==0 ||i==j)
                 printf("*");
              else
                printf(" ");
        }
          printf("\n");      
         }
    }
    else
        printf("Forma Invalida\n");

}

My program always gives as output "Invalid form" even if Voce type "t" or "q"... I wonder why this is happening.

  • I ran the posted function as a program and it worked right. The character comparison you’re doing is right. It could be junk, try using fflush(stdin) before the printf.

  • which printf? the first?

  • Voce thinks the string is garbage value?

  • Yes it can happen, after all you have a large program with several functions. Try to use the command before the first printf. Try to run the function alone as I did and then tell me the result.

  • Weird! It really works ...

  • But there’s no way to solve for the big show?

  • The fflush(stdin) did not resolve?

Show 2 more comments

1 answer

3


What happens is that stdin is with the character you had typed in the main function to choose the function q311, a "enter". And a enter really is not a "t" or a "q".

The simplest way to fix this is by making the scanf ignore "enter" by adding a space before the type:

scanf(" %c",&forma);

I recommend two readings:

One question our.

A material external.

  • Thank you very much, fflush(stdin) had not worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.