使用while(1)的简单代码中的错误

时间:2014-04-01 19:01:33

标签: c

我的while(1)循环实现中有一些错误。这可能是一个愚蠢的问题,但我无法实现这个问题。

int main()
{
    char choice;
    unsigned short item = 0;

    while(1)
    {
            printf("\nSingly Linked List\n");
            printf("\n1. Add an item to the list");
            printf("\n2. Remove an item from the list");
            printf("\n3. Search for an item in the list");
            printf("\n4. Print the list");
            printf("\n5. Exit\n");
            scanf("%c",&choice);
            switch(choice)
            {
                    case '1':
                            printf("\nYet to be implemented\n");
                            break;
                    case '4':
                            printf("\nYet to be implemented\n");
                            break;
                    case '5':
                            return 0;
                    default:
                            printf("\nInvalid, please do re-enter\n");
            }
    }
    return 0;

}

当我运行此代码时,我将输出为

  

单链表

     
      
  1. 将项目添加到列表
  2.   
  3. 从列表中删除项目
  4.   
  5. 搜索列表中的项目
  6.   
  7. 列印清单
  8.   
  9. 退出
  10.   

现在无论我输入什么输入除了5,在执行特定情况后,在下一个循环中打印菜单并自动接受一些输入并执行默认情况。然后它再次显示菜单,最后我得到控件输入我的输入。

  

1

     

尚未实施

     

单链表

     
      
  1. 将项目添加到列表
  2.   
  3. 从列表中删除项目
  4.   
  5. 搜索列表中的项目
  6.   
  7. 列印清单
  8.   
  9. 退出
  10.         

    无效,请重新输入

         

    单链表

         
        
    1. 将项目添加到列表
    2.   
    3. 从列表中删除项目
    4.   
    5. 搜索列表中的项目
    6.   
    7. 列印清单
    8.   
    9. 退出
    10.   

4 个答案:

答案 0 :(得分:3)

在%c之前添加一个空格,将换行符留在输入黄油中,在下一次迭代中,scanf将读取并使用它,导致循环继续。

scanf(" %c",&choice);

答案 1 :(得分:1)

永远不要使用scanf来带来很多复杂功能。 fegts()可以帮助您免除现在遇到的所有麻烦。

答案 2 :(得分:0)

你也必须消耗你按下的输入。尝试:

scanf(" %c", &choice);

代替。此外,您应该测试scanf是否遇到错误情况,因此请再次更改:

if(scanf(" %c", &choice) != 1)
    return 0;

或者,使用模式"%c\n"

答案 3 :(得分:0)

这是一个类似问题的好答案:

https://stackoverflow.com/a/7898516/2769157

问题在于你必须点击返回发送输入,并且仍然位于输入缓冲区中,如下所述:

http://c-faq.com/stdio/scanfc.html

此线程中的答案通过使用返回字符来起作用:

scanf(" %c",&choice);

这里有一个快速修改,可以看到添加的角色:

int main()
{
    char choice;
    unsigned short item = 0;
    char str[15];

    while(1)
    {
            printf("\nSingly Linked List\n");
            printf("\n1. Add an item to the list");
            printf("\n2. Remove an item from the list");
            printf("\n3. Search for an item in the list");
            printf("\n4. Print the list");
            printf("\n5. Exit\n");
            scanf("%c",&choice);
            sprintf(str,"%d",choice);
            printf("%s",str);
相关问题