用户输入用作函数c ++中的参数
User input used as a parameter in a function c++
虽然我明白为什么我的代码是错误的以及我的暴力破解方法,但我想知道是否有办法按照我想象的方式来做,所以:
(仅供参考,我正在制作一个名为“河内塔”的简单游戏,这是我在手动输入堆栈作为参数时创建的功能)
void putOn(std::stack<int> &first, std::stack<int> &second){
if(first.empty()){
std::cout << "Your stack is empty, try again";
}else if(first.top() && second.empty()){
second.push(first.top());
first.pop();
}else if(first.top() < second.top()){
second.push(first.top());
first.pop();
}else if(first.top() > second.top()){
std::cout << "You can only put larger pieces on top." << std::endl;
}
}
稍后在我的代码中我使用 switch-case(用于输入、移动塔等)我想做的是将我的行 putOn(x,y)
转换为变量输入,如下所示:
case 1:
char a,b;
std::cout << "Enter the tower u want to move from(x, y, z): ";
std::cin >> a;
std::cout << std::endl;
std::cout << "To(x, y, z): ";
std::cin >> b;
std::cout << std::endl;
// putOn(&a,&b);
// putOn(a,b);
break;
你可以告诉我我要去哪里,显然我收到一条错误消息:candidate function not viable: no known conversion from 'char *' to 'std::stack<int> &' for 1st argument void putOn(std::stack<int> &first, std::stack<int> &second){
是否有一种“类似于python”的方式来执行此操作,我的用户输入直接将字符变量 a
和 b
转换为 x,y
或 z
作为参数,谢谢你的时间
试试这个:
std::map<char, std::stack<int>*> m = {{'x', &x}, {'y', &y}, {'z', &z}};
//...
putOn(*m[a], *m[b]);
虽然我明白为什么我的代码是错误的以及我的暴力破解方法,但我想知道是否有办法按照我想象的方式来做,所以:
(仅供参考,我正在制作一个名为“河内塔”的简单游戏,这是我在手动输入堆栈作为参数时创建的功能)
void putOn(std::stack<int> &first, std::stack<int> &second){
if(first.empty()){
std::cout << "Your stack is empty, try again";
}else if(first.top() && second.empty()){
second.push(first.top());
first.pop();
}else if(first.top() < second.top()){
second.push(first.top());
first.pop();
}else if(first.top() > second.top()){
std::cout << "You can only put larger pieces on top." << std::endl;
}
}
稍后在我的代码中我使用 switch-case(用于输入、移动塔等)我想做的是将我的行 putOn(x,y)
转换为变量输入,如下所示:
case 1:
char a,b;
std::cout << "Enter the tower u want to move from(x, y, z): ";
std::cin >> a;
std::cout << std::endl;
std::cout << "To(x, y, z): ";
std::cin >> b;
std::cout << std::endl;
// putOn(&a,&b);
// putOn(a,b);
break;
你可以告诉我我要去哪里,显然我收到一条错误消息:candidate function not viable: no known conversion from 'char *' to 'std::stack<int> &' for 1st argument void putOn(std::stack<int> &first, std::stack<int> &second){
是否有一种“类似于python”的方式来执行此操作,我的用户输入直接将字符变量 a
和 b
转换为 x,y
或 z
作为参数,谢谢你的时间
试试这个:
std::map<char, std::stack<int>*> m = {{'x', &x}, {'y', &y}, {'z', &z}};
//...
putOn(*m[a], *m[b]);