如何一次从文件中读取两个十六进制值
How to read two hex values from a file at a time
我正在尝试从一个文件中读取两个数据,但我遇到了两个问题:
- 无限循环
- 第一个值读取正确,第二个值不正确。
我尝试使用 getline,但无法正常工作。我已将我的代码包含在 c++ 中、输入文件和下面的正确输出。
正确的输出应该是这样的:
Num1 = 4FD37854
Num2 = E281C40C
我正在尝试从名为 input.txt:
的文件中读取两个数据
4FD37854
E281C40C
这是我的程序:
#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;
}
那么,我们来看第二个问题
- The second value read is for some reason read incorrectly.
嗯,这实际上是一个输入问题。你输入的是0xE281C40C,而int的最大值是0x7FFFFFFF。您可以简单地将 newFloat 的定义更改为:
union newfloat{
float f;
unsigned int i;
};
它会接受大于 0x7FFFFFFF 的值
- Infinite loop
我不知道为什么会这样,我的机器上也没有。不过,在您解决第二个问题后,它可能不会在您的机器上发生。
while (!myfile.eof())
几乎总是错的,而且会比你预期的多读一遍。
你应该说
while(myfile >> hex >> x1.i >> x2.i)
但主要问题是E281C40C不能读成int
,你需要一个unsigned int
。
这也是你的无限循环的原因 - 因为读取失败 在 到达文件末尾之前, !myfile.eof()
保持为真,并且读取保持失败。
这是避免 eof()
.
的另一个原因
我正在尝试从一个文件中读取两个数据,但我遇到了两个问题:
- 无限循环
- 第一个值读取正确,第二个值不正确。
我尝试使用 getline,但无法正常工作。我已将我的代码包含在 c++ 中、输入文件和下面的正确输出。
正确的输出应该是这样的:
Num1 = 4FD37854
Num2 = E281C40C
我正在尝试从名为 input.txt:
的文件中读取两个数据4FD37854
E281C40C
这是我的程序:
#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;
}
那么,我们来看第二个问题
- The second value read is for some reason read incorrectly.
嗯,这实际上是一个输入问题。你输入的是0xE281C40C,而int的最大值是0x7FFFFFFF。您可以简单地将 newFloat 的定义更改为:
union newfloat{
float f;
unsigned int i;
};
它会接受大于 0x7FFFFFFF 的值
- Infinite loop
我不知道为什么会这样,我的机器上也没有。不过,在您解决第二个问题后,它可能不会在您的机器上发生。
while (!myfile.eof())
几乎总是错的,而且会比你预期的多读一遍。
你应该说
while(myfile >> hex >> x1.i >> x2.i)
但主要问题是E281C40C不能读成int
,你需要一个unsigned int
。
这也是你的无限循环的原因 - 因为读取失败 在 到达文件末尾之前, !myfile.eof()
保持为真,并且读取保持失败。
这是避免 eof()
.