while 循环中的高级 switch 语句?

发布于 2024-08-31 06:57:06 字数 802 浏览 6 评论 0原文

我刚刚开始学习 C++,但对其他语言有一些先验知识(不幸的是,不久前使用了 vb),但遇到了一个奇怪的困境。我不喜欢使用这么多 IF 语句,想使用 switch/cases,因为它看起来更干净,我想实践一下.. 但是..

可以说我有以下场景(理论代码):

while(1) {

  //Loop can be conditional or 1, I use it alot, for example in my game
  char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      break;
    case 'b':
      cout << "...";
      break;
  }
}

这就是我的问题。假设我想退出 WHILE 循环,它需要两个 Break 语句吗?

这显然看起来是错误的:

case 'a':
  cout << "You entered A, which is correct";
  break;
  break;

那么我只能在 'a' 上执行 IF 语句来使用 break; 吗?我错过了一些非常简单的事情吗?

这将解决我现在遇到的很多问题。

I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But..

Lets say I have the following scenario (theorietical code):

while(1) {

  //Loop can be conditional or 1, I use it alot, for example in my game
  char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      break;
    case 'b':
      cout << "...";
      break;
  }
}

And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements?

This obviously looks wrong:

case 'a':
  cout << "You entered A, which is correct";
  break;
  break;

So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple?

This would solve a lot of my problems that I have right now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

蓬勃野心 2024-09-07 06:57:06

我会将检查重构为另一个函数。

bool is_correct_answer(char input)
{
    switch(input)
    {
    case 'a':
        cout << "You entered A, which is correct";
        return true;
    case 'b':
        cout << "...";
        return false;
    }
    return false;
}

int main()
{
    char input;
    do
    {
        std::cout << "Enter something\n -->";
        std::cin  >> input;
    } while (!is_correct_answer(input));
}

I would refactor the check into another function.

bool is_correct_answer(char input)
{
    switch(input)
    {
    case 'a':
        cout << "You entered A, which is correct";
        return true;
    case 'b':
        cout << "...";
        return false;
    }
    return false;
}

int main()
{
    char input;
    do
    {
        std::cout << "Enter something\n -->";
        std::cin  >> input;
    } while (!is_correct_answer(input));
}
不可一世的女人 2024-09-07 06:57:06

您可以简单地让 while 循环检查在 case 语句之一中设置的 bool 值。

bool done = false;    
while(!done)
{
 char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      done = true; // exit condition here
      break;
    case 'b':
      cout << "...";
      break;
  }
}

You could simply have the while loop check for a bool value that is set within one of your case statements.

bool done = false;    
while(!done)
{
 char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      done = true; // exit condition here
      break;
    case 'b':
      cout << "...";
      break;
  }
}
忘羡 2024-09-07 06:57:06

是的,C 和 C++ 没有办法说“退出多个可破坏块”(其中“可破坏块”是任何循环或开关)。解决方法包括 goto 和使用布尔变量来记录外部“可破坏块”是否也应该破坏(两者都不优雅,但这就是生活)。

Yes, C and C++ have no way to say "exit multiple breakable blocks" (where a "breakable block" is any loop or switch). Workarounds include gotos and use of boolean variables to record whether an outer "breakable block" should also break (neither is elegant, but, that's life).

划一舟意中人 2024-09-07 06:57:06

两个 break 语句不会让您退出 while 循环。第一个 break 只能让您跳出 switch 语句,而第二个则永远不会到达。

您需要的是使 while 循环的条件为 false,假设 switch 语句之后的循环中没有任何内容。如果 switch 后面还有其他代码,则应该检查 switch 后面的条件,并在那里break


bool done = false;

while(! done)
{
  // do stuff
  switch(something)
  {
    case 'a':
    done = true;  // exit the loop 
    break;
  }

  //  do this if you have other code besides the switch
  if(done)
   break;  // gets you out of the while loop

  // do whatever needs to be done after the switch

}

Two break statements will not get you out of the while loop. The first break only gets you out of the switch statement and the second one is never reached.

What you need is to make the condition of the while loop false, assuming that there is nothing in the loop after the switch statement. If there is other code after the switch, you should check the condition after the switch, and break there.


bool done = false;

while(! done)
{
  // do stuff
  switch(something)
  {
    case 'a':
    done = true;  // exit the loop 
    break;
  }

  //  do this if you have other code besides the switch
  if(done)
   break;  // gets you out of the while loop

  // do whatever needs to be done after the switch

}

心凉 2024-09-07 06:57:06

您可以尝试:

  • 使用标志
  • 使用 Goto
  • 将内部 Breakable 块放入函数中
  • 使用异常
  • 使用 longjump 和 setjmp

与此问题非常相似的主题

http://www.gamedev.net/community/forums/topic.asp?topic_id=385116

You could try:

  • Using Flags
  • Using Goto
  • Having the Inner Breakable block into a function
  • Using Exceptions
  • Using longjump and setjmp

A topic very similar to this question

http://www.gamedev.net/community/forums/topic.asp?topic_id=385116

眼睛会笑 2024-09-07 06:57:06

您可能对 C++ 中的命名循环习惯感兴趣。

#define named(blockname) goto blockname; \
                         blockname##_skip: if (0) \
                         blockname:

#define break(blockname) goto blockname##_skip;

named(outer)
while(1) {

  //Loop can be conditional or 1, I use it alot, for example in my game
  char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      break(outer);
    case 'b':
      cout << "...";
      break(outer);
  }
}

You might be interested in the named loop idiom in C++.

#define named(blockname) goto blockname; \
                         blockname##_skip: if (0) \
                         blockname:

#define break(blockname) goto blockname##_skip;

named(outer)
while(1) {

  //Loop can be conditional or 1, I use it alot, for example in my game
  char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      break(outer);
    case 'b':
      cout << "...";
      break(outer);
  }
}
Spring初心 2024-09-07 06:57:06

您还可以将循环封装到函数中,并在 case 内调用 return,以防打破 while 的标志还不够。
对于某些人来说这不是一个好的编程习惯,但是如果你保持函数简单,我不明白为什么不这样做。

You can also encapsulate the loop into a function and call return inside the case, for the case that the flag breaking the while is not enough.
It is not a good programming practice for some people but if you keep the function simple I don't see why not.

叶落知秋 2024-09-07 06:57:06

您可以用稍微过度设计的 OO 解决方案来替换交换机......

#include <iostream>
#include <map>
#include <set>

class input_responder
{
    std::set<char> correct_inputs;
    std::map<char, const char*> wrong_inputs;

public:

    input_responder()
    {
        correct_inputs.insert('a');
        wrong_inputs['b'] = "...";
    }

    bool respond(char input) const
    {
        if (correct_inputs.find(input) != correct_inputs.end())
        {
            std::cout << "You entered " << input << ", which is correct\n";
            return true;
        }
        else
        {
            std::map<char, const char*>::const_iterator it = wrong_inputs.find(input);
            if (it != wrong_inputs.end())
            {
                std::cout << it->second << '\n';
            }
            else
            {
                std::cout << "You entered " << input << ", which is wrong\n";
            }
            return false;
        }
    }
};

int main()
{
    const input_responder responder;
    char input;
    do
    {
        std::cout << "Enter something\n -->";
        std::cin  >> input;
    } while (responder.respond(input) == false);
}

You could replace the switch with a slightly over-engineered OO solution...

#include <iostream>
#include <map>
#include <set>

class input_responder
{
    std::set<char> correct_inputs;
    std::map<char, const char*> wrong_inputs;

public:

    input_responder()
    {
        correct_inputs.insert('a');
        wrong_inputs['b'] = "...";
    }

    bool respond(char input) const
    {
        if (correct_inputs.find(input) != correct_inputs.end())
        {
            std::cout << "You entered " << input << ", which is correct\n";
            return true;
        }
        else
        {
            std::map<char, const char*>::const_iterator it = wrong_inputs.find(input);
            if (it != wrong_inputs.end())
            {
                std::cout << it->second << '\n';
            }
            else
            {
                std::cout << "You entered " << input << ", which is wrong\n";
            }
            return false;
        }
    }
};

int main()
{
    const input_responder responder;
    char input;
    do
    {
        std::cout << "Enter something\n -->";
        std::cin  >> input;
    } while (responder.respond(input) == false);
}
堇年纸鸢 2024-09-07 06:57:06

您可以将交换机更改为 ifsystem。无论如何它都会被编译成同样的东西。

You could change your switch to an ifsystem. It will be compiled to the same thing anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文