我正在为大学项目编写基于文本的拼字游戏实现。
规范声明用户的位置输入必须从单行读取,如下所示:
Coordinates of the word's first letter and orientation (<A – P> <1 – 15> <H ou V>): G 5 H
G 5 H
是用户对该特定示例的输入。如图所示,顺序必须是 char
int
char
。
读取用户输入的最佳方式是什么?
cin >> row >> column >> orientation
如果用户搞砸了,将导致崩溃。
getline
和后续的 string
解析器是一个有效的解决方案,但需要做一些工作。
是否有另一种更好的方法来做到这一点,我想念的是什么?
感谢您的宝贵时间!
最佳答案
getline
和解析不一定要增加很多工作。由于您已经知道如何从流中读取(更正)数据,只需使用 getline
读取一行,然后从该行创建一个 istringstream
并从那里读取。
我要补充的一件事是,创建一个类来保存特定移动的数据并为该类重载 operator>>
以读取数据可能非常有意义一招。粗略的草图应该是这样的:
class move {
char row;
int column;
char orientation;
public:
friend std::istream &operator>>(std::istream &is, move &m);
};
std::istream &operator>>(std::istream &is, move &m) {
std::string temp;
std::getline(is, temp);
std::istringstream buffer(temp);
// Now we can parse data from buffer just like we could from another stream.
return is;
}
至少目前,我还没有包含任何错误处理代码。根据您的挑剔程度,这可能会有些棘手(例如,如果来自 stringstream
的输入失败,则在原始输入流中设置失败位)。
关于C++ 初学者 - 从命令行读取 3 个连续值的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835092/