TyCharm
TyCharm

Reputation: 425

C: Input displaying multiple times

I am writing a program that prints out a square or triangle of a certain width/height and something really weird is happening. If I don't enter the correct characters to begin the program (S, T, or Q), the input will display again but will repeat itself depending on how many characters I type in incorrectly. Here's my code:

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

void print_square(int n, char c) {
for (int i=0; i < n; i++) {
    for (int j=0; j < n; j++) {
        printf("%c", c);
    }
    printf("\n");
}
}

void print_triangle(int n, char c) {
int count = 1;
for (int i=0; i < n; i++) {
    for (int j=0; j < count; j++) {
        printf("%c", c);
    }
    count = count + 1;
    printf("\n");
}
}

int main(int argc, const char * argv[]) {

int n;
char cmd;
char c;

do {

    printf("Enter T for a triangle, S for a square, "
           "Q to quit: ");
    scanf("%c", &cmd);
    cmd = toupper(cmd);

    if (cmd == 'S' || cmd == 'T') {
        printf("Enter the size: ");
        scanf("%d", &n);
        printf("Enter the character: ");
        scanf(" %c", &c);

        if (cmd == 'S') {
            print_square(n, c);
        }

        else {
            print_triangle(n, c);
        }
    }

} while (cmd != 'T' && cmd != 'S' && cmd != 'Q');

return 0;
}

Any idea what's causing this?

Upvotes: 0

Views: 449

Answers (1)

Vu VAnh
Vu VAnh

Reputation: 70

Remember when you input you have to do 1 step :

1 - enter character

2 - enter "Enter" which means "\n"

When you use scanf ("%c") it store character in cmd. When you input 'a' you will press 'a' and enter'\n', a will store in cmd. '\n' will store in stack. As you can see this does not match the condition so the loop happend and the step

printf("Enter T for a triangle, S for a square, " "Q to quit: ");

happend. Then it will store '\n' in cmd because the following is scanf("%c",cmd). It run again and loop again.

My suggestion for this is to use getchar() after scanf() in this situation. It will throw the unwanted '\n'away.

Upvotes: 1

Related Questions