Alex napsal:
Hi,
I want to read in enum types from standard input. Unfortunately it does not
work. The code is given as follows:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
enum TYP { eins, zwei, drei};
int main()
{
string input("datIn");
ifstream IN(input.c_str());
TYP t;
cin >t; // Fehlermeldung
return 0;
}
Do I have to define an input operator ?
Thank you for your help.
It depends on format in which is your enum written in the stream.
Anyway you should overload input operator>>:
template<typename T, typename TRAITS>
std::basic_istream<T, TRAITS>& operator>>(std::basic_istream<T,
TRAITS>& is, TYP& data)
{
// Here read your type from is any way you want.
// One possible (of many) example follows:
std::basic_string<Ts;
is >s;
// Here would be better some searching mechanism or table for
bigger enums
if (s == "eins") data = eins;
else if (s == "zwei") data = zwei;
else if (s == "drei") data = drei;
else
{
// Wrong input - do what ever you want, but you should switch
is into bad state
}
return is;
}
It is written from scratch, so there may be some typos.