0
votes

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.

1
type != 'c' || type != 'd' || type != 'i' will always be true.1201ProgramAlarm
Also the check on scanf return value is strange. You actually seem to ignore it, since you print the value of the variable that will be for sure not set if return value is ` != 2`.Roberto Caboni
regarding: if (scanf("%d %c", &input, &type) != 2) { printf("TYPE IS: %c\n", type); } That call to printf() should be a call to fprintf( stderr, "some error message\n");user3629249
regarding: if(type != 'c' || type != 'd' || type != 'i') This is not the correct logic. Suggest: if(type != 'c' && type != 'd' && type != 'i')user3629249
regarding: sum = (sizeof(input)) + sum; the variable input is an int which will always be (depending on the underlying hardware architecture) 4 or 8user3629249

1 Answers

1
votes

Replace

if(type != 'c' || type != 'd' || type != 'i')

By

if(type != 'c' && type != 'd' && type != 'i')