0

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.

moesef
  • 4,091
  • 16
  • 45
  • 66

4 Answers4

1

temp is an int. So you see the encoded ascii values after casting the char to an int.

StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399
0

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() )
Cheers and hth. - Alf
  • 135,616
  • 15
  • 192
  • 304
0

This does not do what you think it does:

while(!file.eof())

This is covered in Why is iostream::eof inside a loop condition considered wrong?, so I won't cover it in this answer.

Try:

char c;
while (file >> c)
{
    // [...]
}

...instead. Reading in a char rather than an int will also save you having to convert the representation (ASCII value 49 is 1, etc...).

Community
  • 1
  • 1
Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
0

For the record, and despite this being the nth duplicate, here's how this code might look in idiomatic C++:

for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);

    std::cout << "We read:";

    for (std::string n; std::getline(iss, line, ','); )
    {
        std::cout << " " << n;

        // now use e.g. std::stoi(n)
    }

    std::cout << "\n";
}

If you don't care about lines or just have one line, you can skip the outer loop.

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025