Jenny
Jenny

Reputation: 85

Character comparison in C?

When I pass in one of the characters I specified, it returns 2 as if it was an incorrect character? Am I comparing these incorrectly?

int valid_character(char character) {
    if (character == '*' || character == '%' || character == '#') {
        return 1;
    } else {
        return 2;
    }
}

edit:

The problem is where I am calling the function:

if (selection == 1) {
    printf("Enter character, width and length: ");
    scanf("%c %d %d", &c, &width, &length);
    putchar(c);
    int response = valid_character(c);
    if (response == 1) {
        draw_rectangle(width, length, c);
    } else {
        printf("%d", response);
        printf("Invalid data provided.");
    }
}

When I call putchar(c); it prints out 1 even though I am passing in % Why is this?

Upvotes: 0

Views: 67

Answers (1)

chqrlie
chqrlie

Reputation: 145297

You did not post the whole function! you probably had another scanf before the code fragment that left a pending \n in the input stream.

As you found out yourself, you can skip this \n and any other white space by reading the character with:

scanf(" %c%d%d", &c, &width, &length);

Upvotes: 1

Related Questions