条件未在循环中求值

Condition is not evaluated in loop

本文关键字:循环 条件      更新时间:2023-10-16

条件语句的目的是打印出一个简单的基于文本的菜单,然后存储用户的输入,并将其评估为循环的条件。

如果不满足条件,则应提示用户输入一个整数,这将导致条件为true。相反,它只是退出循环。

我已经试过了,如果循环来完成任务的话。

这是代码:

#include "stdafx.h"
// Namespaces
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::iostream;
using std::ostream;
using std::string;
// Variables
const string new_game = "Start a new game";
const string continue_game = "Continue your game";
const string load_save = "Load a save";
int menu_choice = 0;
const string choice_description = "You choice to";
// MAIN Program
int _tmain(int argc, _TCHAR* argv[]) 
{
    cout << "Welcome to The Forgotten Time" <<endl;
    cout << "You have the following options" << endl;
    while (menu_choice < 1 || menu_choice > 3 )
        {
        cout << "1." << new_game << endl;
        cout << "2." << continue_game << endl;
        cout << "3." << load_save << endl;
        cin >> menu_choice;
        }
    switch (menu_choice)
    {
        case 1: cout << choice_description << new_game;
        case 2: cout << choice_description << continue_game;
        case 3: cout << choice_description << choice_description;
    }
    cin.ignore();
    cin.get();
    return 0;
}

最后,我希望能够将条件语句组合成一个函数并通过switch语句来创建一个句子,该句子评估用户输入并显示他们的选择。

最初设置:

int menu_choice = 0; 

然后你问:

if (menu_choice < 1 || menu_choice > 4 )

该选项小于1,因此输入if block
然后获得一些用户输入并退出应用程序。

您的代码中根本没有循环。只是一个将返回真值的初始条件语句,因为:

menu_choice=0;

并且,

if(menu_choice<1 ||...)

You don't need a "return" statement, either. Put in a switch() after your if(). Also, you could just remove the second if() condition and put your whole main() content in a while() or do..while() loop. Also, a switch is pretty efficient if you have a menu based display that takes in certain specific discrete-set of values.

Remove your if condition, instead use a do while loop.

do{
cout << "1." << new_game << endl; 
cout << "2." << continue_game << endl;
cout << "3." << load_save << endl;
cin >> menu_choice;
} 
while (menu_choice!=0);