Search code examples
c++filefstreamifstreamreadfile

How to read two hex values from a file at a time


I am trying to read two data from a file and I am experiencing two problems:

  1. Infinite loop
  2. The first value is read correctly, the second is not.

I tried playing around with getline but I couldn't get it to work properly. I have included my code in c++, the input file, and the correct output below.

The correct output should be this:

Num1 = 4FD37854
Num2 = E281C40C

There are the two data I'm trying to read from a file called input.txt:

4FD37854
E281C40C

Here is my program:

#include <iostream>
#include <fstream>

using namespace std;

union newfloat{
    float f;
    unsigned int i;
};

int main ()
{

// Declare new floating point numbers
newfloat x1;
newfloat x2;

// Create File Pointer and open file (destructor closes it automatically)
ifstream myfile ("input.txt");

while (myfile >> hex >> x1.i) // Read until at EOF
{

myfile >> hex >> x2.i; // Read input into x2

cout << "Num1 = " << hex << x1.i << endl;
cout << "Num2 = " << hex << x2.i << endl;

} // end of file reading loop
return 0;
}

Solution

  • while (!myfile.eof()) is almost always wrong, and will read one more time than you expect.

    You should say

    while(myfile >> hex >> x1.i >> x2.i)
    

    But the main issue is that E281C40C can't be read into an int, you need an unsigned int.

    This is also the reason for your infinite loop - since the read fails before reaching the end of the file, !myfile.eof() keeps being true, and the reading keeps failing.
    Which is one more reason to avoid eof().