C ++文本文件读取 [英] C++ Text File Reading

查看:233
本文介绍了C ++文本文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要一些帮助,我目前有一个文本文件,其中包含以下数据:

So I need a little help, I've currently got a text file with following data in it:

myfile.txt
-----------
b801000000

我想要做的是读取b801等..数据为位,所以我可以得到值

What I want to do is read that b801 etc.. data as bits so I could get values for

0xb8 0x01 0x00 0x00 0x00.

当前我使用下面的typedef读取这行到一个无符号字符串。

Current I'm reading that line into a unsigned string using the following typedef.

typedef std::basic_string <unsigned char> ustring;
ustring blah = reinterpret_cast<const unsigned char*>(buffer[1].c_str());

我不断下降的是试图获取每个char {'b','8' ...}真的是{'0xb8','0x01'等...}

Where I keep falling down is trying to now get each char {'b', '8' etc...} to really be { '0xb8', '0x01' etc...}

任何帮助都很感激。

感谢。

推荐答案

我看到两种方法:


  1. 打开文件 std :: ios :: binary 并使用 std :: ifstream ::在使用标志 std :: ios_base :: hex 之后提取十六进制双字节,并提取到两个字节大的类型的操作符>< (如 stdint.h 的(C ++ 0x / C99)uint16_t或等效)。使用 std :: stringstream 的例子看看@ neuro的注释你的问题。 std :: ifstream 将几乎相同地工作。

  1. Open the file as std::ios::binary and use std::ifstream::operator>> to extract hexadecimal double bytes after using the flag std::ios_base::hex and extracting to a type that is two bytes large (like stdint.h's (C++0x/C99) uint16_t or equivalent). See @neuro's comment to your question for an example using std::stringstreams. std::ifstream would work nearly identically.

直接访问流迭代器并手动执行转换。

Access the stream iterators directly and perform the conversion manually. Harder and more error-prone, not necessarily faster either, but still quite possible.

这篇关于C ++文本文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆