gpt4 book ai didi

c++ - 从缺少列的文件中读取数据。 C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:18 25 4
gpt4 key购买 nike

基本上我有一个包含 8 列的数据文件,我想将每一列的每个值放入一个数组变量中。但问题是缺少某些值。例如

100 54201.10 49392 9379101 10381.1372
101 5823829 73929 83729.77

缺失值由额外的制表符或/t 空格隔开。我如何才能读取这些值,忽略丢失的数据并将正确的值输入到可用的正确变量中?

我尝试使用:

infile >> network;
string val = isNaN(network);
if (count % 8 == 0) { ID[count / 8] = val; }
if (count % 8 == 1) { time[count / 8] = val; }
if (count % 8 == 2) { country_code[count / 8] = val; }
if (count % 8 == 3) { sms_in[count / 8] = val; }
if (count % 8 == 4) { sms_out[count / 8] = val; }
if (count % 8 == 5) { call_in[count / 8] = val; }
if (count % 8 == 6) { call_out[count / 8] = val; }
if (count % 8 == 7) { internet[count / 8] = val; }
count++;

最佳答案

在 C++ 中执行此操作的一个好方法是使用 getline 获取每一行。

#include <string>
#include <vector>
...
typedef struct {
unsigned long id;
unsigned long timestamp;
...
} Record;
std::vector<Record> records;
while (std::getline(std::cin, s)) {
...

然后使用substr填写记录集合。假设您的字段是制表符分隔的并且数字左对齐,那么您可以像这样处理默认设置。

posTab = s.find_first_of('\t');
records[i].id = posTab == 0
? defaultID
: std::atoi(s.substr(0, posTab).c_str());

索引 i 是记录索引,从 0 开始。对于 float 和 double float ,您需要用适当的标准数值解析器替换 std::atoi。

如果数据是制表符分隔的,对于(每条记录的)每个字段,使用 find_first_of(posTab + 1, '/t') 查找每个字段的开头,从您可以保存在 posPreviousTab 中的前一个位置开始用作相等性测试和第一个 substr 参数而不是零。

注意事项

对于大型数据集和在某些条件下,std::list 比 std::vector 更快。您可以编写测试来比较您的案例的两个选项。

如果您正在处理大数据,您可能需要更高的速度,使用 char[MAXSIZE] 和 C 中的等效算法并即时处理,而不是将每条记录都存储在内存中。

关于c++ - 从缺少列的文件中读取数据。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com