user4765116
user4765116

Reputation:

C++ ifstream class get() method returns the character?

I have this code

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv) {
    ifstream in;
    in.open(*(argv+1));
    char c;

    while (true) {
        if (in.eof())
            break;
        c = in.get();
        cout << c;
    }
    in.close();

    return 0;
}

I read the file which is passed via the command line as the first argument. While reading the file, I get the char '?' as the last one. Why?

If I remove this line

in.open(*(argv+1));

I will get only the char '?'.

Upvotes: 3

Views: 28845

Answers (2)

vsoftco
vsoftco

Reputation: 56567

In the while loop you end up reading eof:

c = in.get(); // reads eof
cout << c;

This is not the best way to read a text file, use

while(in >> c) { /* process c here */ }

or

while(in >> std::noskipws >> c) { /* process c here */ } 

if you want the white spaces (like \n) included.

If your file is in binary, then it doesn't make too much sense to display it, but if you want, then use get() but test if(!in) break; before further processing

c = in.get();
if (!in) break; // test the stream
cout << c;      // then process

If you just want to display the file, the easiest way is to use the stream buffer directly, like

std::cout << in.rdbuf(); // display the whole file at once

Related: Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

Upvotes: 9

Thomas Matthews
Thomas Matthews

Reputation: 57728

The istream::get() method returns an untranslated value from the input stream.

If the value is not printable, your console may translate the character to '?'.

A better method is to print the value of the character along with the character:

cout << "\'" << c << "\', 0x" << hex << ((unsigned int) c) << endl;

This will allow you to see unprintable characters.

Upvotes: 1

Related Questions