c++ - 从选择的语句中删除选择

标签 c++ loops if-statement

基本上我想要做的是让用户输入 1-3 之间的数字,当输入该数字时,if 语句 将执行..

但是,我希望这个循环遍历所有 cookie(它确实如此),直到每个人都被选中并且不能选择相同的数字。如果您查看我的代码并能解释我应该怎么做,将不胜感激?

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    string luck;
    int cookies = 3;
    int choice;
    int *taken;

    for (int i = 0; i < 3; i++) {

        cout << "What cookie do you want?";
        cin >> choice;

        if (choice == 1) {
            cout << "Tomorrow is a day";
        }
        if (choice == 2) {
            cout << "Tomorrow can be cool";
        }
        if (choice == 3) {
            cout << "Summer is coming";
        }
        choice--; //not working though, something wrong im doing i guess.
    }
    return 0;
}

最佳答案

您需要一个容器来跟踪已采取的措施。例如:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string luck;
    int choice;
    std::map< int, std::string > cookies {
       { 1, "Tomorrow is a day" },
       { 2, "Tomorrow can be cool" },
       { 3, "Summer is coming" }
    };

    while( cookies.size() ) {
        cout << "What cookie do you want? [";
        for_each( cookies.begin(), cookies.end(), []( std::map< int, string >::value_type & v ) { cout << v.first << ','; } );
        cout << ']';
        cin >> choice;

        std::map< int, std::string >::iterator iter( cookies.find( choice ) );
        if( iter == cookies.end() )
            cout << "Sorry, that cookie has been taken" << endl;
        else {
            cout << iter->second << endl;
            cookies.erase( iter );
        }
    }
    return 0;
}

关于c++ - 从选择的语句中删除选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880941/

相关文章:

javascript - Laravel:在 blade @if 中使用 Javascript

c++ - 为什么我要关心 boost 文档中的 EXTENSION 注释

javascript - 在不终止浏览器的情况下退出无限循环

java - 在 Java 中使用随机数生成器循环

php - 通配符数组比较——提高效率

javascript - AJAX 调用完成后如何执行操作?

c++ - 虚幻引擎中的链接错误

c++ - C++中的字符到整数的转换

c++ - 挣扎着将新内容分配给 vector 的指针

java - 将括号添加到字符串中的字符序列