for(;;)vs do..while()用于主程序循环

时间:2019-07-19 22:36:57

标签: c++

我正在使用do..while循环来允许我的程序在条件正确的情况下退出,但是我在学校里的示例中看到为了退出而抛出了异常。这些示例使用了常规的无限for循环。我在想可以使用if语句从for循环中中断,而不是抛出,但是我不确定。下面的代码:

// main.cpp

import pygame

# --- constants --- (UPPER_CASE_NAMES)

BLACK = (0, 0, 0)  

SURFACE_WIDTH = 1054  
SURFACE_HEIGHT = 562  

# --- functions --- (lower_case_names)

def move_target(target_img, target_rect):
    alive = True  
    clock = pygame.time.Clock()
    while alive:

        # --- events ---

        for event in pygame.event.get():  
            if event.type == pygame.QUIT:  
                alive = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    alive = False

        # --- updates/changes ---

        keys_pressed = pygame.key.get_pressed()  

        if keys_pressed[pygame.K_LEFT]:  
            target_rect.x -= 5  
        if keys_pressed[pygame.K_RIGHT]:  
            target_rect.x += 5  
        if keys_pressed[pygame.K_UP]:  
            target_rect.y -= 5  
        if keys_pressed[pygame.K_DOWN]:  
            target_rect.y += 5

        # --- draws ---

        surface.fill(BLACK)
        surface.blit(target_img, target_rect)
        pygame.display.update()

        # the same game's speed on all computers = 60 FPS
        clock.tick(60)

# --- main --- (lower_case_names)

pygame.init()  

pygame.display.set_caption('Robot Apocalypse')  
surface = pygame.display.set_mode((SURFACE_WIDTH, SURFACE_HEIGHT))  

target_img = pygame.image.load('target.png')  
target_img = pygame.transform.scale(target_img, (40, 40))  
target_rect = target_img.get_rect()  

move_target(target_img, target_rect)

pygame.quit()  

//命令。h

#include <cstdlib>
#include <iostream>
#include <string>

#include "commands.h"

using namespace std;

int main(int argc, char *argv[]) {
    bool exit = false;

    try {
        do {
            try {
                // Read a line, break at EOF, and echo print the prompt
                // if one is needed.
                string line;
                getline(cin, line);
                if (cin.eof()) {
                    cout << endl;
                    break;
                }

                command_fn fn = find_command_fn(line);
                fn();
            }
            catch (command_error& error) {
                // If there is a problem discovered in any function, an
                // exn is thrown and printed here.
                cout << error.what() << endl;
            }
        } while (!exit);
    }
    catch (exception& e) {

    }

    return 0;
}

// commands.cpp

#ifndef __COMMANDS_H__
#define __COMMANDS_H__

#include <unordered_map>
using namespace std;


// A couple of convenient usings to avoid verbosity.

using command_fn = void (*)();
using command_hash = unordered_map<string,command_fn>;

// command_error -
//    Extend runtime_error for throwing exceptions related to this 
//    program.

class command_error: public runtime_error {
   public: 
      explicit command_error (const string& what);
};

// execution functions -

void fn_connect     ();
void fn_disconnect  ();
void fn_test        ();
void fn_exit        ();

command_fn find_command_fn (const string& command);


#endif

编辑:包括了更多的来源。我有很多空白,因为我正在重写一个通过UDP发送数据的程序。我只是在寻找有关如何安全退出程序的一些建议。

1 个答案:

答案 0 :(得分:0)

do...while完全等效于for循环,除了测试是在循环的末尾而不是在开始处进行的,因此do...while总是至少运行一次。在这两种情况下,您都可以使用break退出循环。您不需要引发异常,但是可以。如果您有多个层次,通常更容易引发异常并在循环中捕获并中断,或者设置终止条件,或者在循环外捕获也会终止的异常。