简体   繁体   English

从fstream读取十六进制值到int

[英]reading hex values from fstream into int

I have a text file which has one hex value in each line. 我有一个文本文件,每一行都有一个十六进制值。 Something like 就像是

80000000
08000000
0a000000

Now i am writing a c++ code to read this directly. 现在,我正在编写一个c ++代码以直接阅读它。 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. 尽管某些数字已正确填充,但ch逻辑还是有缺陷的。 Can anybody tell me the right way of doing it. 谁能告诉我正确的做法。 I basicaly need to populate an array with the int equivalent. 我基本上需要用int等价物填充数组。

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. 注意:我必须将a的类型更改为unsigned int因为它溢出了int并因此导致循环失败。

80000000:

As a hex value this sets the top bit of a 32 bit value. 作为十六进制值,它将设置32位值的高位。 Which on my system overflows an int (sizeof(int) == 4 on my system). 我系统上的哪个溢出一个int(我系统上的sizeof(int)== 4)。 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; 在OP循环中,这将导致无限循环,因为从不设置EOF。 in the loop above it will never enter the main body and the code will exit. 在上面的循环中,它将永远不会进入主体,并且代码将退出。

fstream :: operator >>将忽略空格,因此您不必担心换行。

... and the way to change it is to use noskipws : f >> std::noskipws; ...更改它的方法是使用noskipwsf >> std::noskipws; will set no skipping of whitespace until you use std::skipws manipulator. 除非使用std::skipws操纵器,否则不会设置空白。

But why do you want to read the '\\n' ? 但是,为什么要阅读'\\n' To make sure that there is one number per line? 确保每行有一个号码? Is it necessary? 有必要吗?

As mentioned, extracting whitespace manually in the code you've shown is unnecessary. 如上所述,在显示的代码中手动提取空格是不必要的。 However, if you do come across a need for this in the future, you can do so with the std::ws manipulator. 但是,如果将来确实需要此功能,则可以使用std::ws操作器来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM