c - while、switch、case语句

标签 c while-loop switch-statement

我正在为我的菜单使用 whileswitchcase 语句,当它运行时它一直说输入选择,我知道while(1) 创建了一个无限循环,但有没有办法避免这种情况?

while(1)
{
    printf("\nEnter Choice \n");
      scanf("%d",&i);
      switch(i)
      {
            case 1:
            {
             printf("Enter value to add to beginning: ");
             scanf("%c",&value);
             begin(value);
             display();
             break;
             }
             case 2:
             {
             printf("Enter value to add last: ");
             scanf("%c",&value);
             end(value);
             display();
             break;
             }
             case 3:
             {
             printf("Value to enter before\n");
             scanf("%c",&loc);

             printf("Enter value to add before\n");
             scanf("%c",&value);

             before(value,loc);
             display();
             break;
             }
             case 4 :
             {
             display();
             break;
             }

      }
}

如有任何帮助,我们将不胜感激。

最佳答案

While(1) 没问题。但是你必须有一些条件才能完成循环。喜欢:

while(1){
.........
if(i == 0)
  break;
............
}

在每个“%d”和“%c”的开头添加一个空格,因为scanf总是在缓冲区中留下一个换行符:

"%d"->" %d" 
"%c"->" %c"

关于c - while、switch、case语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474795/

相关文章:

bash - 在 bash 中遍历文件时保留空格

assembly - PIC汇编器中如何进行bank切换?

c - 这段代码有什么问题吗?段错误: 11

javascript - 字符串化数组是一个好习惯吗?

c - 为什么在此 C 反向 shell 代码中需要 dup2?

C++ 访问 URL 的最快方法

使用 Ragel 解析器捕获字段

java - 在 C 中创建 jobobject 不起作用

c - 为什么“while(!feof(file))”总是错误的?

Java 二十一点投注和发牌并没有按照我的预期进行