问题描述
我有一个文本文件,每行有一个十六进制值。像
80000000
08000000
0a000000
现在我正在写一个c ++代码来直接读取它。 SOmething像
fstream f(filename,ios :: in);
while(!f.eof)
{
int x;
char ch;
f>> std :: hex>> x>> ch; //具有ch的意图是读取'\\\
'
}
现在这不工作按预期。虽然一些数字正在填充正确,ch逻辑是有缺陷的。任何人都可以告诉我正确的做法。
我需要填充一个与int等价的数组。
$ b
#include< iostream>
#include< fstream>
int main()
{
std :: ifstream f(AAPlop);
unsigned int a;
while(f>> std :: hex>> a)///注意循环是如何完成的。
{
std :: cout<< I(}
}
注意:我必须更改 a 到 unsigned int ,因为它溢出 int
80000000:
b
$ b作为十六进制值,这将设置32位值的顶部位。在我的系统上溢出一个int(我的系统上的sizeof(int)== 4)。这将流设置为坏状态,没有进一步的阅读工作。在OP循环中,这将导致无限循环,因为EOF从未设置;在上面的循环中它将永远不会进入主体,代码将退出。
I have a text file which has one hex value in each line. Something like
80000000 08000000 0a000000Now i am writing a c++ code to read this directly. SOmething like
fstream f(filename, ios::in); while(!f.eof) { int x; char ch; f>>std::hex>>x>>ch; // The intention of having ch is to read the '\n' }Now this is not working as expected. While some of the numbers are getting populated properly, the ch logic is flawed. Can anybody tell me the right way of doing it.I basicaly need to populate an array with the int equivalent.
解决方案This works:
#include <iostream> #include <fstream> int main() { std::ifstream f("AAPlop"); unsigned int a; while(f >> std::hex >> a) /// Notice how the loop is done. { std::cout << "I("<<a<<")\n"; } }Note: I had to change the type of a to unsigned int because it was overflowing an int and thus causing the loop to fail.
80000000:As a hex value this sets the top bit of a 32 bit value. Which on my system overflows an int (sizeof(int) == 4 on my system). This sets the stream into a bad state and no further reading works. In the OP loop this will result in an infinite loop as EOF is never set; in the loop above it will never enter the main body and the code will exit.
这篇关于从fstream读取十六进制值到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!