【问题标题】:While-loop in C re-printing previous statementsC中的while循环重新打印以前的语句
【发布时间】:2021-11-06 11:33:19
【问题描述】:

运行代码时,while 循环会重新打印提示,要求用户在打印矩形之前选择一个选项和尺寸,此时它应该打印形状,然后遍历提示。 while 循环中的什么会导致那些 printf 语句重新打印?

代码:

#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

【问题讨论】:

  • 输入userOption号码后按下回车按钮的代码在哪里?
  • 我正在尝试具有程序功能,以便在打印形状后再次提示用户,但在打印形状之前再次重新打印提示。试图了解如何解决这个问题。
  • 通过处理输入userOption 后按下的回车按钮来修复它,以便您的代码正确解析输入。
  • 这能回答你的问题吗? scanf() leaves the new line char in the buffer

标签: c loops while-loop char scanf


【解决方案1】:

如果我理解正确,那么您需要在scanf 的调用中更改格式字符串

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

到下面

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

请参阅转换说明符 %c 之前的空白。它允许跳过空白字符,例如可以通过按 Enter 键出现在输入缓冲区中的换行符 '\n'

【讨论】:

  • 进行此修复后完美运行,猜我没有考虑回车键。谢谢!