如何根据C ++中文件的输入为枚举分配一个值? [英] How to assign a value to an enum based on input from a file in C++?
本文介绍了如何根据C ++中文件的输入为枚举分配一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,其值包括:START和STOP。我也有以下枚举:
I have a file with values like: START and STOP. I also have the following enum declared:
enum Type {
START,
STOP
};
我试图将枚举设置为与文件中的第一个值相同:
I'm trying to set the enum equal to the first value in the file with something like this:
enum Type foo;
ifstream ifile;
ifile.open("input.txt");
ifile >> foo;
我收到错误:在'ifile >> foo中没有匹配'operator >>' '。
I'm getting the error: no match for ‘operator>>’ in ‘ifile >> foo’.
如何正确执行此操作?
推荐答案
我发现我的特殊情况是以下代码是最好的解决方案:
I've found for my particular situation that the following code is the best solution:
template <class T> T a2e(string c, const string a[], const int size) {
for (int i=0; i < size; i++) {
if (c == a[i]) {
return static_cast<T>(i);
}
}
}
并将使用如下:
enum StateType {START, STOP};
const int MAXVALUES = STOP+1;
const string stateNames[MAXVALUES] = {"START", "STOP"};
enum StateType state;
ifstream ifile;
ifile.open("input.txt");
ifile >> foo;
state = a2e <enum StateType> (foo, stateNames, MAXVALUES);
希望这有助于将来的人。感谢大家就如何解决这个问题提出建议。
Hope this helps someone in the future. Thanks to everyone who made suggestions about how to tackle this problem.
这篇关于如何根据C ++中文件的输入为枚举分配一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文