在 c++ 中从文本文件中读取两个十六进制值
Reading two hex values from text file in c++
我有一个按以下方式格式化的文件:
0x10c3 0xad6066
0x10c7 0xad6066
0x10c1 0xad6066
0x10c5 0xad6066
0x10c3 0xad6066
我想将第一个值读取到数组输入 [] 中,将第二个值读取到数组参数 []。
我尝试了以下方法:
while(getline(f, line)){
stringstream ss(line);
getline(ss, input[i], ' ');
getline(ss, param[i]);
}
我收到的错误如下 错误:调用"getline(std::stringstream&, uint16_t&, char("没有匹配函数
我正在尝试将字符串保存到整数数组中。那么,如何将字符串保存到整数数组中。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <memory>
#include <vector>
#include <iterator>
#include <algorithm>
struct Foo {
int a;
int b;
};
std::istream &operator>>(std::istream &input, Foo &data)
{
return input >> std::hex >> data.a >> std::hex >> data.b;
}
std::ostream &operator<<(std::ostream &output, const Foo &data)
{
return output << std::hex << data.a << " - " << std::hex << data.b;
}
template<typename T>
std::istream &readLineByLine(std::istream &input, std::vector<T> &v)
{
std::string line;
while(std::getline(input, line)) {
std::istringstream lineStream { line };
T data;
if (lineStream >> data) {
v.push_back(data);
}
}
return input;
}
int main() {
std::vector<Foo> v;
readLineByLine(std::cin, v);
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>{ std::cout, "n" });
return 0;
}
https://wandbox.org/permlink/6PLekmBL5kWPA9Xh
你可以这样做:
while(getline(f, line)){
// splitting
std::string first = line.substr(0, line.find(" "));
std::string last = line.substr(line.find(" ") + 1);
// print result
std::cout<<"First: " << first << std::endl << "Last: " << last << std::endl;
}
如果您的数组被定义为存储(无符号(整数值(例如unsigned int input[MAX], param[MAX];
( 您可以使用std::istringstream
,例如:
std::istringstream iss;
for(int i = 0; i < MAX; i++){
if(!getline(f, line)) break;
iss.str(line);
iss >> std::hex >> input[i] >> param[i];
std::cout<< std::hex << input[i] << " " << param[i] << std::endl;
}
不要忘记添加
#include <sstream>
在源代码文件中。
相关文章:
- 在 c++ 中从文本文件中读取两个十六进制值
- 两个派生类(十六进制 二进制)的虚拟功能
- 如何将多个十六进制值连接到一个值
- 如何添加两个或多个字符的十六进制值
- 超过两个数字十六进制
- C 将向量转换为2个十六进制,然后将其存储在字符串中
- 上两个六角形将视觉转换和分开2个字节六角形,上两个角色,下两个十六进制在C 中转到第二个Charater
- 在 C++ 中存储为字符串的两个十六进制值上的 XOR
- 从文件中读取 4 个十六进制值并转换为浮点数
- 将2个十六进制值组合为1个十六进制
- 连接两个十六进制数字
- 在一行代码中输入2个十六进制数字和一个字符串
- 为什么这个程序的结果是三个十进制数"597, 295, 295,"输入两个十六进制数"255 127<enter>"
- strtol对两个不同的十六进制字符串给出相同的答案
- 将十六进制拆分为 2 个十六进制值
- 将文件中的两个十六进制字符组合并转换为十进制
- 同时向QByteArray添加多个十六进制数字
- c++中两个十六进制数字的相加
- 将字节转换为两位十六进制数字
- 将8个十六进制字符转换为4-uint8_t数组的最有效方法