简体   繁体   English

如何在c ++中使用fstream从文件中读取十六进制值?

[英]How to read hex values from a file using fstream in c++?

As the title says, how do you read hex values using fstream ?正如标题所说,您如何使用fstream读取十六进制值?

i have this code: (let's say we have "FF" in the file.)我有这个代码:(假设我们在文件中有“FF”。)

fstream infile;
infile.open(filename, fstream::in|fstream::out|fstream::app);

int a;
infile >> std::hex;
infile >> a;
cout << hex << a;

but this does not give me any output instead of ff .但这并没有给我任何输出而不是ff I know there is a fscanf(fp, "%x", val) but I am curious is there any way to do this using stream library.我知道有一个fscanf(fp, "%x", val)但我很好奇有没有办法使用流库来做到这一点。

UPDATE :更新

My code was right all along, it turns out my error was I couldn't read "FFF" and put it in variable a,b,c like this我的代码一直都是正确的,结果我的错误是我无法读取"FFF"并将其放入变量 a,b,c 中

while (infile >> hex >> a >> b >> c)
  {
    cout << hex << a << b << c << "\n";
  }

Can somebody help me with this?有人可以帮我解决这个问题吗? do I have to separate every HEX values i want to read with space?我是否必须用空格分隔我想读取的每个十六进制值? because infile >> hex >> setw(1) doesn't work..因为infile >> hex >> setw(1)不起作用..

You can use the hex modifier您可以使用十六进制修饰符

int n;
cin >> hex >> n;

This works:这有效:

int main()
{
    const char *filename = "blah.txt";
    ifstream infile(filename, fstream::in);

    unsigned int a;
    infile >> hex >> a;
    cout << hex << a;
}

你必须在阅读时链接std::hex ,就像你在写作时链接它一样:

infile >> std::hex >> a;

Also make sure that your input file is written using a Hex editor and not a regular text editor.还要确保您的输入文件是使用十六进制编辑器而不是常规文本编辑器编写的。 Otherwise a file foo.txt containing a character 'a' will be read as 0x61 and printed as 0x61 instead of 0xa.否则,包含字符 'a' 的文件 foo.txt 将被读取为 0x61 并打印为 0x61 而不是 0xa。 A nice Hex editor for linux is "Bless".一个不错的 linux 十六进制编辑器是“Bless”。

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

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