Read in enum types

A

Alex

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.
 
D

dasjotre

Alex said:
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 ?

You could read an int and convert it to TYP
 
H

Haro Panosyan

Alex said:
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());

As a side note, you can directly do this, instead of above 2 lines
ifstream IN("datIn);
 
O

Ondra Holub

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<T> s;
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top