Re: Better way to use istream to read an ascii value into a char.
"Markus Schoder" <a3vr6dsg-usenet@yahoo.de> wrote in message
news:1146769880.776128.109260@y43g2000cwc.googlegroups.com...
Jim Langston wrote:
In one of my files I am outputting the value of a char into a human
readable
file. That is,
char a = 123;
std::ofstream CharFile( ("Players\\" + Name + ".char").c_str());
if ( CharFile.is_open() )
CharFile << (int) a;
So the file has the character a stored as "123".
That was the easy part, now comes the fun of reading it back into the
char.
I tried a number of things and finally wound up doing this:
std::istream& operator >>( std::istream& is, char& Byte )
{
int temp;
is >> temp;
Byte = temp;
return is;
}
char a;
std::ifstream CharFile( ( "Players\\" + CharName + ".char" ).c_str());
if ( CharFile.is_open() )
CharFile >> a;
[snip]
The thing I don't like about overriding the operator >> for a char,
though,
is if I ever want to actually write a char as a byte itself (which I
don't
think I will).
I'm just wondering if there is a better way.
<snip>
Wrap a char reference in a user defined type and define operator>> for
this type:
#include <iostream>
struct achar
{
achar(char &c) : c_(c) {}
char &c_;
};
std::istream &
operator>>(std::istream &is, achar a)
{
int tmp;
is >> tmp;
a.c_ = tmp;
return is;
}
int
main()
{
char c;
std::cin >> achar(c);
std::cout << c << std::endl;
}
Ahh, perfect, thanks! I'm sure you meant
std::istream &
operator>>(std::istream &is, achar& a)