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

19,806

Solution 1

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) // test the stream
    break;
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 considered wrong?

Solution 2

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.

Share:
19,806
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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 '?'.