简体   繁体   English

运行一个简单的 C++ 函数

[英]Running a simple C++ function

I've just started learning the basics in C++ and currently am trying to make a program that does a few basic things.我刚刚开始学习 C++ 的基础知识,目前正在尝试制作一个执行一些基本操作的程序。 The problem I have is occurring in the pasted function below.我遇到的问题发生在下面的粘贴函数中。

At this point it literally does nothing when it runs.在这一点上,它在运行时实际上什么都不做。 All I'm trying to do it make it so the function runs over and over again forever, until the user enters the letter 'q'.我正在尝试做的所有事情都是为了让该功能一遍又一遍地运行,直到用户输入字母“q”。

The function must keep running even if the user enters some random string, anything, 'q' is the only keystroke that should stop the loop.即使用户输入一些随机字符串,该函数也必须继续运行,任何东西,'q' 是唯一应该停止循环的击键。

I have tried toying around with 'cin.whatever" and haven't found success. If you have an answer please provide as much explanation as possible. Thank you!我试过玩弄“cin.whatever”,但没有成功。如果您有答案,请提供尽可能多的解释。谢谢!

void menu()
{
    cin.clear();
    cin.ignore();
    char quit = 'w';
    while (quit != 'q') // while loop to allow the user infinite tries
    {
        cout << "Which story would you like to play? Enter the number of the story (1, 2, or 3) or type q to quit: " << endl;
        cin >> quit;

        if (quit < '1' or quit > '3') // make sure the user picks a valid choice
        {
            cout << "Valid choice not selected." << endl;
        }
        if (quit == '1')
        {
            story1(); // run story 1
        }
        if (quit == '2')
        {
            story2(); // run story 2
        }
        if (quit == '3')
        {
            story3(); // run story 3
        }
        if (quit == 'q')
        {
            cout << "good bye" << endl;
            break;
        } 
    }
}

Try adding single quotes around your 1,2,3 like you did with the q.尝试像使用 q 一样在 1,2,3 周围添加单引号。 The cin is expecting a char to be entered so evaluate it as such. cin 期望输入一个字符,因此对其进行评估。 eg: if (quit == '1')例如: if (quit == '1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM