C++ 如何在c ++中使用fstream从文件中读取十六进制值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5040681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read hex values from a file using fstream in c++?
提问by ardiyu07
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
. I know there is a fscanf(fp, "%x", val)
but I am curious is there any way to do this using stream library.
但这并没有给我任何输出而不是ff
. 我知道有一个,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)
不起作用..
采纳答案by Bernd Elkemann
You can use the hex modifier
您可以使用十六进制修饰符
int n;
cin >> hex >> n;
回答by Oliver Charlesworth
This works:
这有效:
int main()
{
const char *filename = "blah.txt";
ifstream infile(filename, fstream::in);
unsigned int a;
infile >> hex >> a;
cout << hex << a;
}
回答by Nekresh
You have to chain std::hex
when reading, the same way you chain it for writing :
你必须std::hex
在阅读时链接,就像你在写作时链接它一样:
infile >> std::hex >> a;
回答by Than21
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 nice Hex editor for linux is "Bless".
还要确保您的输入文件是使用十六进制编辑器而不是常规文本编辑器编写的。否则,包含字符 'a' 的文件 foo.txt 将被读取为 0x61 并打印为 0x61 而不是 0xa。一个不错的 linux 十六进制编辑器是“Bless”。