如何从键盘读取一个完整的随机文本,过滤和投射
How to read from keyboard a complete random text, filter and cast
我正在为学校开发一款 Tic Tac Toe 游戏,但开发一种以实用且格式良好的方式从键盘读取游戏的好方法变得越来越困难。
这是我做的:
Human::play() const
{
int pos
std::cout << endl << Name << ", please, insert the desirable move:";
//^^this is a class atribute
std::string keyboard;
std::stringstream ss;
std::getline(std::cin, keyboard);
ss << keyboard[0];
ss >> pos;
return (pos);
}//end of Human class method *play*
这个函数将被调用,我将验证玩家的移动是否可以接受,因此,看看它是否在 0 和 8 之间。另外,我想检查是否有 "r" 或 "q" 的条目,因为这意味着玩家想要返回一回合或退出游戏。
为了检查玩家是否输入了这个指令,我这样做了,即:
int playermove = player1.play()
if (playermove == 'q')
...
我遇到了麻烦,因为根据上面显示的内容,输入字符时 pos 返回 0。但是,我没有看到任何实际的解决方案。
你能给我一些替代方案吗?
您可以检查 r
和 q
,如果为假,只需减去 -48(因为 ASCII table)。
看看这个:
#include <iostream>
using namespace std;
int main() {
char tmp;
cin >> tmp;
if(tmp == 'q') {
cout << tmp;
return 0;
} else {
int smth = tmp;
cout << smth - 48;
return 0;
}
return 0;
}
这将捕获 q
和数字。然后,您可以通过检查 (> -48 && < -39).
来检查 (smth - 48) 是否在 0-9 范围内
我正在为学校开发一款 Tic Tac Toe 游戏,但开发一种以实用且格式良好的方式从键盘读取游戏的好方法变得越来越困难。
这是我做的:
Human::play() const
{
int pos
std::cout << endl << Name << ", please, insert the desirable move:";
//^^this is a class atribute
std::string keyboard;
std::stringstream ss;
std::getline(std::cin, keyboard);
ss << keyboard[0];
ss >> pos;
return (pos);
}//end of Human class method *play*
这个函数将被调用,我将验证玩家的移动是否可以接受,因此,看看它是否在 0 和 8 之间。另外,我想检查是否有 "r" 或 "q" 的条目,因为这意味着玩家想要返回一回合或退出游戏。
为了检查玩家是否输入了这个指令,我这样做了,即:
int playermove = player1.play()
if (playermove == 'q')
...
我遇到了麻烦,因为根据上面显示的内容,输入字符时 pos 返回 0。但是,我没有看到任何实际的解决方案。
你能给我一些替代方案吗?
您可以检查 r
和 q
,如果为假,只需减去 -48(因为 ASCII table)。
看看这个:
#include <iostream>
using namespace std;
int main() {
char tmp;
cin >> tmp;
if(tmp == 'q') {
cout << tmp;
return 0;
} else {
int smth = tmp;
cout << smth - 48;
return 0;
}
return 0;
}
这将捕获 q
和数字。然后,您可以通过检查 (> -48 && < -39).