jeudi 26 décembre 2019

scanf() in loop with a conditional does not work

I'm making a simple program that returns the sum of the sizes of user input. User first inputs an int for amount of sizeof() sums to add Followed by an input and char for data type. This all works, BUT, what fails is if user types in anything other than 'c', 'd' or 'i' loop breaks and prints "invalid tracking code type."

My program fails on the conditional - even though the scanf() correctly obtains the char, it still fails.

FOR EXAMPLE:

INPUT:

3
10 i
7 c
12 d

OUTPUT

143 bytes

INPUT

1
1 o

OUTPUT

invalid tracking code type

how can you compare a user input using scanf in a loop?

#include <stdio.h>

int main()
{
    int num, input, i, sum;
    int invalid = 1;
    sum = 0;
    i = 0;
    char type;

    printf("give me a num!\n");
    scanf("%d", &num);

    while(i < num)
    {
        printf("int and char?\n");
        //scanf("%d", &input);
        //scanf(" %c\n", &type);
        if (scanf("%d %c", &input, &type) != 2)
        {
            printf("TYPE IS: %c\n", type);


        }
        printf("TYPE IS: %c\n", type);
        if(type != 'c' || type != 'd' || type != 'i')
        {
            printf("invalid tracking code type");
            invalid = 0;
            break;
        }
        i++;
        //printf("what is i? %d\n", i);
        sum = (sizeof(input)) + sum;
        printf("IT's the sum %d\n", sum);

    }

    if(invalid != 0)
    {
    printf("%d bytes", sum);
    }

    return 0;
}

There are a number of other posts that answer similar issues, but wasn't able to find anything specifically for this issue.

I've tried a number of things such as separating the scanf(), using different types of operators for the conditional. It works fine without the conditional, but with the conditional it always returns "invalid tracking code type" even when they are correct.

Aucun commentaire:

Enregistrer un commentaire