我正在寻找一种简单的方法,使用流从文本文件中读取十六进制值。我在 Stack Overflow 上搜索了“C++ hex read stream 0x”,大多数回答都是关于将十六进制写为文本或在没有“0x”前缀的情况下读取十六进制值。这个问题是关于将带有“0x”前缀的十六进制数作为一个数字一次性读取。
我的方法:
unsigned char byte;
std::istringstream sample("0xce");
sample >> std::hex >> byte;
第一个字符对应的byte
值为'0'(0x30)。
'strtol`函数处理转换,但需要读取数据,并将其转换为C风格字符串。
我正在重载一个类中的operator>>
,以读取逗号分隔值(CSV)文本文件。这是数据文件的示例:
1,-4.93994892,0xa5,8,115.313e+3,
2,-4.93986238,0xc0,8,114.711e+3,
3,-4.93977554,0xc2,8,114.677e+3,
我的提取方法:
class Csv_Entry
{
public:
friend std::istream& operator >>(std::istream& inp, Csv_Entry& ce);
unsigned int m_index;
double m_time;
unsigned char m_byte;
unsigned int m_data_length;
double m_bit_rate;
};
std::istream&
operator >> (std::istream& inp, Csv_Entry& ce)
{
char separator;
inp >> ce.m_index;
inp >> separator;
inp >> ce.m_time;
inp >> separator;
inp >> std::hex >> ce.m_byte;
inp >> separator;
inp >> ce.m_data_length;
inp >> separator;
inp >> ce.m_bit_rate;
inp.ignore(10000, '\n');
return inp;
}
我需要使用 std::setw
吗?
编辑1:
我正在使用 Windows 7 上的 Visual Studio 2010 Premium,64位平台。