基本上我想要做的是让用户输入 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/