【问题标题】:While loop not executing code in correct order in C [duplicate]虽然循环没有在C中以正确的顺序执行代码[重复]
【发布时间】:2020-09-01 05:01:27
【问题描述】:

我是学习 C 语言的新手。 我已经从 C++ 转移并正在实现 while 并执行 while 循环

以下是我的代码中的一个 sn-p。这在 C++ 中运行良好,但在 C 中执行 while 循环后,一旦它首先执行 scanf 然后打印菜单,我无法弄清楚。请帮忙

#include <stdio.h>

int main() {
    int ch;
    char ans='y';
    while(ans=='y'){
        
        printf("\n1. Insert / Create linked list ");
        printf("\n2. Insert at specific position ");
        printf("\n3. Display ");
        printf("\n4. Search element");
        printf("\n5. Delete element");
        printf("\n6. Exit");
        printf("\nEnter choice \n");
        
        scanf("%d",&ch);
      
        switch(ch)
        {
            case 1 :
                break;
                
            case 2 :
                break;
            
            case 3 :
                break;
                
            case 4 :
                break;
                
            case 5 :
                break;
                
            case 6 :
                break;
        }
        
        printf("\nDo you want to continue ?\n");
        scanf(" %c ",&ans);
        printf("\n");
     };
    
    return 0;
}

【问题讨论】:

  • scanf() 格式字符串中的尾随空格是可怕的——当输入应该是交互式的时更是如此。您必须在输入数字后键入一些不是空格的字符——因此用户必须在当前输入之前猜测/知道下一个输入应该是什么(scanf(" %d ", &amp;ch); 将终止。

标签: c while-loop do-loops


【解决方案1】:

scanf(" %c ",&amp;ans); --> scanf(" %c",&amp;ans); 删除尾随空格。

ans 之后无需寻找空格。

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2011-01-19
    相关资源
    最近更新 更多