0

when running the code, the while loop is re-printing the prompts asking for the user to pick an option and dimensions before printing the rectangle, when it should print the shape and then iterate through the prompts. What in the while loop would be causing those printf statements to re-print?

Code:

#include "testFile.h"

int draw_rectangle(char sym, int wid, int len){
    
    if((wid == 0) || (len == 0)){
        printf("Invalid data provided 2\n");
        return 0;
    }else{
        int i;
        int j;
        for(i = 1; i <= wid; i++){
            for(j = 1; j <= len; j++){
                printf("%c", sym);
            }
            printf("\n");
        }
        return 1;
    }
}


int main(){
    
    int loopTrue = 1;
    char character;
    int length, width;
    int userOption = 4;
    
    
    while(loopTrue == 1){
        printf("Enter 1(rectangle), 2(triangle, 3(other), 0(quit): ");
        scanf("%d", &userOption);
        
        if(userOption >= 4){
            printf("Invalid data operation 1 \n");
        }else if(userOption == 0){
            printf("bye bye");
            loopTrue = 0;
        }else if(userOption == 1){
            printf("enter a character, width, and length: ");
            scanf("%c %d %d", &character, &width, &length);
            draw_rectangle(character, width, length);
        }else if(userOption == 2){
            printf("not done\n");
        }else if(userOption == 3){
            printf("not done\n");
        }
        
    }
    return 0;
    
}

Heres the Output

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Where is the code to handle the enter button pushed after entering the `userOption` number? – David Schwartz Sep 09 '21 at 20:26
  • I'm trying to have the program function so that the user is given the prompt again after the shape is printed, but the prompt is re-printed again before the shape is printed. Trying to understand how to fix that. – akthedev Sep 09 '21 at 20:27
  • Fix it by handling the enter button pushed after entering the `userOption` so that your code correctly parses the input. – David Schwartz Sep 09 '21 at 20:28
  • Does this answer your question? [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – Adrian Mole Sep 15 '21 at 09:59

1 Answers1

3

If I have understood correctly then you need to change the format string in this call of scanf

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

to the following

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

See the blank before the conversion specifier %c. It allows to skip white space characters as for example the new line character '\n' that can appear in the input buffer by pressing the Enter key.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335