将文件中的值存储到数组中,并根据特定数字提取值

Storing values from file into array and extract values based on certain number

本文关键字:数字 提取 数组 文件 存储      更新时间:2023-10-16

file.txt

0 00 19
0 200 699
0 7000 8499
0 85000 89999
0 900000 949999
0 9500000 9999999
1 00 09
1 100 399
1 4000 5499
1 55000 86979
1 869800 998999
1 9990000 9999999
2 00 19
2 200 349
2 35000 39999
2 495 699
2 7000 8399
2 84000 89999
2 900000 949999
2 9500000 9999999
3 00 02
3 030 033
3 0340 0369
3 03700 03999
3 04 19
3 200 699
3 7000 8499
3 85000 89999
3 900000 949999
3 9500000 9999999

假设我只想要第一个值3的块,我怎么能只将以下内容存储到三个单独的数组中:

3 00 02
3 030 033
3 0340 0369
3 03700 03999
3 04 19
3 200 699
3 7000 8499
3 85000 89999
3 900000 949999
3 9500000 9999999  

到目前为止,我有:

while (finished != EOF){
    finished = fscanf(fp,"%d %s %sn", &areaScanned, &pubLow, &pubHigh);
}

这工作正常,但它存储整个列表。我怎样才能缩小范围?基本上我需要做的是检查某个数字是否落在第 1 行的值之间,第 1 列和第 2 列之间,然后是第 2 行,值介于 col1 和 col2 之间,然后是行 3,值介于 col1 和 col2 之间等。

首先,您可能不想使用 fscanf 。其次,你几乎肯定不想使用三个单独的数组,如果你能帮上忙的话。如果可能的话,你想要这样的东西:

struct whatever { 
    int a, b, c;
    friend std::istream &operator>>(std::istream &is, whatever &w) { 
        return is >> w.a >> w.b >> w.c;
    }
};
std::vector<whatever> w;
std:copy_if(std::istream_iterator<whatever>(infile),
            std::istream_iterator<whatever>(),
            std::back_inserter(w),
            [](whatever const &w) { return w.a == 3; } );