枚举类型不能接受 CIN 命令
enum type can not accept cin command
请看这段代码:
#include <iostream>
using namespace std;
int main()
{
enum object {s,k,g};
object o,t;
cout << "Player One: "; cin >> o;
cout << "Player Two: "; cin >> t;
if (o==s && t==g) cout << "The Winner is Player One.n";
else if (o==k && t==s) cout << "The Winner is Player One.n";
else if (o==g && t==k) cout << "The Winner is Player One.n";
else if (o==g && t==s) cout << "The Winner is Player Two.n";
else if (o==s && t==k) cout << "The Winner is Player Two.n";
else if (o==k && t==g) cout << "The Winner is Player Two.n";
else cout << "No One is the Winner.n";
return 0;
}
编译时,我会得到这个错误:no match for 'operator>>' in 'std::cin >> o
我正在使用代码块。那么这段代码有什么问题呢?
枚举没有运算符>>()。您可以自己实现一个:
std::istream& operator>>( std::istream& is, object& i )
{
int tmp ;
if ( is >> tmp )
i = static_cast<object>( tmp ) ;
return is ;
}
当然,如果你只输入一个整数并投射自己会更容易。只是想向您展示如何编写 cin>>运算符。
您是否希望能够键入"s","k"或"g"并将它们解析为枚举类型? 如果是这样,则需要定义自己的流运算符,如下所示:
std::istream& operator>>(std::istream& is, object& obj) {
std::string text;
if (is >> text) {
if (text == "s") {
obj = s;
}
// TODO: else-if blocks for other values
// TODO: else block to set the stream state to failed
}
return is;
}
如果您不熟悉运算符重载概念并希望快速修复,只需使用:
scanf("%d%d", &o, &t);
相关文章:
- 从命令行c++发送文本文件名
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 使用QProcess执行命令,并将结果存储在QStringList中
- 数组长度,为什么从命令行获取时不能使用它?
- Problems with std::cin.fail()
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- clang整洁10忽略了我的NOLINT命令
- 使用 (cin) 用户输入将其粘贴到 std::system 中,并在另一个终端中运行带有输入的命令
- 在 C++ 中使用 if(cin>>) 命令
- std::cin 无法将命令行中的用户输入传递给具有 char 类型的变量吗?
- 在C++中,有没有一种简单的方法可以通过iostream::cin获取带有参数的命令调用
- 枚举类型不能接受 CIN 命令
- 命令'cin'和'cout'不起作用
- cin命令导致内存位置出现Microsoft C++异常:std::bad_alloc
- 用一串命令预加载cin
- 我的 CIN 命令完全跳过输入?我什么都试过了