scanf and getchar()

Asked

Viewed 129 times

1

why in the second printf I can use only op=getchar(); but in the end I need to use a scanf to realize the question?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    int i, tab=0;
    char op,  n;
    do {
    printf("\ndigite um numero para ver a tabuada: ");
    scanf("%d", &n);
    getchar();//se livra do ENTER
    printf("\noperacao '*' para multiplicar,  '+' para somar: ");
    op = getchar();
        if(op == '*'){
        for(i=1; i<=10; i++){
            printf("\n%d", n*i);}}
        else if(op == '+'){
            for(i=1; i<=10; i++){
                printf("\n%d", n+i);
            }
        }

    printf("\nquer continuar? [S/N]");
    scanf("%c", &op);
    op= getchar();
    op=tolower(op);
    }while(op != 'n');
    }
  • You used a (perhaps not the best) way to clean the input buffer after scanf("%d", &n); but you did not do the same after scanf("%c", &op);. By the way of the menira as it did will be assigning to op the character ' n' overwriting what was typed (unless it is typed more than ums or N).

  • One way to consume this ' n' is to put in the format of your scanf a space: scanf(" %d", &n); and scanf(" %c", &op); and then you will not need this getchar to consume the.

  • putting a space before the format %c o n (enter) is consumed, as suggested by @anonimo; in the format %d this is not necessary, the spaces and n and t before number digits are automatically consumed

No answers

Browser other questions tagged

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