Search code examples
c++text-filesiostreamfstreamcout

Incorrect char from file


I have the following .txt file:

test.txt

1,2,5,6

Passing into a small C++ program I made through command line as follows:

./test test.txt

Source is as follows:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
    int temp =0;
    ifstream file;
    file.open(argv[1]);

    while(!file.eof())
    {
        temp=file.get();
            file.ignore(1,',');
        cout<<temp<<' ';
    }
    return 0;
}

For some reason my output is not 1 2 5 6 but 49 50 53 54. What gives?

UPDATE:

Also, I noticed there is another implementation of get(). If I define char temp then I can do file.get(temp) and that will also save me converting ASCII representation. However I like using while (file >> temp) so I will be going with that. Thanks.


Solution

  • 49 is the ascii code for digit 49-48 = 1.

    get() gives you a character (character code).

    by the way, eof() only becomes true after a failed read attempt, so the code you show,

    while(!file.eof())
    {
        temp=file.get();
            file.ignore(1,',');
        cout<<temp<<' ';
    }
    

    will possibly display one extraneous character at the end.

    the conventional loop is

    while( file >> temp )
    {
         cout << temp << ' ';
    }
    

    where the expression file >> temp reads in one number and produces a reference to file, and where that file objected is converted to bool as if you had written

    while( !(file >> temp).fail() )