在 c++ 中从文本文件中读取两个十六进制值

Reading two hex values from text file in c++

本文关键字:两个 十六进制 读取 c++ 文本 文件      更新时间:2023-10-16

我有一个按以下方式格式化的文件:

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>

在源代码文件中。