Question

I am having a hard time finding out why I can't read all characters with fstream get function. My code is the following :

ifstream input_stream(input_filename.c_str(), ios::in);
string input;

if(input_stream)
{
    char character;
    while(input_stream.get(character))
    {
        input += character;
    }
    input_stream.close();
}
else
    cerr << "Error" << endl;

By testing a little, I found out that I get a problem when character = 26 (SUB in ASCII) because input_stream.get(26) return false and I get out of my while loop. I would like to put in my string input all characters from the file including SUB. I tryed with getline function at first and I got a similar problem. Could you help me please ?

Was it helpful?

Solution

You need to read a binary stream, not a textual one (since SUB i.e. '0x1a' (that is 26) is a control character in ASCII or UTF8, not a printable one) Use ios::binary at opening time:

 ifstream input_stream(input_filename.c_str(), ios::in | ios::binary);

Maybe you would then code

 do {
   int c= input_stream.get();
   if (c==std::char_traits::eof()) break;
   input += (char)c;
 } while (!input_stream.fail());

Did you consider using std::getline to read an entire line, assuming the input file is still organized in ('\n' terminated) lines?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top