如何从键盘上读取一个完整的随机文本,过滤器和投射
问题描述:
我正在为学校开发一个井字游戏游戏,但它变得越来越困难开发一个很好的方式来从键盘读一个游戏,在一个实用和漂亮的格式办法。如何从键盘上读取一个完整的随机文本,过滤器和投射
这是我做过什么:
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
,并在false上仅减去-48(因为ASCII表)。
检查了这一点:
#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内。