2017-10-13 32 views
0

我有一个do while循环,它由两个开关语句,一些输出代码和一些嵌套while循环来检查输入错误。问题是我想在用户输入'Q'退出时跳过switch语句并跳过其余代码。所以我基本上有两个问题。C++避免布尔标志离开循环,同时使用返回0

  1. 如果我使用do while,那么它会变成返回0和布尔标志(true),这在逻辑上违背了它本身。
  2. 如果我放弃做,而只使用返回0,代码不能执行多次。

我认为这是一个流量问题,而不是语法问题,并想知道如何构建流程以使其成为“干净的代码”。

一个简单的例子:

do { 
    char answer; 
    cout << "Type answer: "; 
    cin >> answer; 

    switch (answer) { 
    case A: 
     cout << "hello"; 
     break; 

    case B: 
     cout << "more weird output"; 
     break; 
    case Q: 
     cout << "Goodbye"; 
     return 0; 
    } 

    cout << "more useless output that I want to skip"; 
    cout << "how does this even work"; 
} while (run); 

在这里,我返回0,这完全否定了一段时间(运行)标志的需要。这是我听说过的糟糕的编码习惯,所以我想知道如何以良好的方式来构造这个结构?

+0

将'return 0'更改为'run = 0'。在底部的东西之前加上'if(!run)break'。请参阅:https://stackoverflow.com/questions/10767927/loop-and-a-half-controlled – stark

回答

-1

在这里,我认为我修复了代码。确保你输入的大写Q不小写。你也忘记了你的字符周围的' '。你的逻辑是正确的 - 只是小错误:) Goodluck!

#include <iostream> 

using namespace std; 


int 
main() 
{ 
    bool run = true; 
    do 
    { 
     char answer; 
     cout << "Type answer: "; 
     cin >> answer; 

     switch (answer) 
    { 
    case 'A': 
     cout << "hello"; 
     break; 

    case 'B': 
     cout << "more weird output"; 
     break; 
    case 'Q': 
     cout << "Goodbye"; 
     return 0; 
    } 

     cout << "more useless output that I want to skip"; 
     cout << "how does this even work"; 
    }while (run); 

    return 0; 
}