简体   繁体   中英

C++ Text File Reading

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

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

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

0xb8 0x01 0x00 0x00 0x00.

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());

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

Any help is appreciated.

Thanks.

I see two ways:

  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::stringstream s. std::ifstream would work nearly identically.

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

strtol使用指定的基数将字符串(需要以N结尾的C字符串)设置为int

Kind of a dirty way to do it:

#include <stdio.h>

int main ()
{
  int num;
  char* value = "b801000000";

  while (*value) {
    sscanf (value, "%2x", &num);
    printf ("New number: %d\n", num);
    value += 2;
  }

  return 0;
}

Running this, I get:

New number: 184
New number: 1
New number: 0
New number: 0
New number: 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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