如何将.txt文件中的未知数字整数保存到数组中

how can i save an unknow number integers from a .txt file into an array

本文关键字:数字 整数 保存 数组 未知数 txt 文件 未知      更新时间:2023-10-16

我生成了一个data.txt文件,其中包含两列中的大量整数。

如何将这些整数保存到数组中?

如果有帮助的话,你可以在这里找到data.txt。样品:

600000
523887 283708
231749 419866
293707 273512
296065 215334
233447 207124
264381 460210
374915 262848
449017 329022
374111 151212
2933 496970

我试过了,但由于某种原因,它不起作用。。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream input("data-for-union-find.txt");
    int i=0;
    float a;
    int size=0;
    size=i/2;
    while (input >> a)
    {i++;
     }
    int *x=new int[size];
    int *y=new int[size+1];
    for(int j=0;j<(size+1);j++)
    {
        input>>x[j];
        input>>y[j];
        cout<<x[j]<<" "<<y[j]<<"              "<<j<<endl;
    return 0;
    }
}

要在数组容量之外添加更多元素,您必须:

  1. 分配一个新的、更大的阵列
  2. 将所有元素从旧数组复制到新数组
  3. 删除旧数组
  4. 附加新元素

一个更安全的解决方案是使用std::vectorpush_back方法。

如果您有大量的数据,您可能需要用较大的大小声明std::vector,以减少重新分配的次数。

我会直接写入一个避免分配的容器:

#include <deque>
#include <iostream>
#include <sstream>
template <typename Sequence>
inline int xvalue(const Sequence& data, std::size_t index) {
    return data[2*index];
}
template <typename Sequence>
inline int yvalue(const Sequence& data, std::size_t index) {
    return data[2*index + 1];
}
int main() {
    std::istringstream stream(""
        "600000n"
        "523887 283708n"
        "231749 419866n"
        "293707 273512n"
        "296065 215334n"
        "233447 207124n"
        "264381 460210n"
        "374915 262848n"
        "449017 329022n"
        "374111 151212n"
        "2933 496970n");
    // Get rid of the suspicious first value:
    int suspicious;
    stream >> suspicious;
    // Use a sequence, which avoids allocations
    std::deque<int> data
    // Read x,y:
    int x;
    int y;
    while(stream >> x >> y) {
        data.push_back(x);
        data.push_back(y);
    }
    // Display:
    for(std::size_t i = 0; i < data.size() / 2; ++i)
        std::cout << "x = " << xvalue(data, i) << ", y = " << yvalue(data, i) << 'n';
    // If you need contiguous memory
    std::vector<int> contiguous(data.begin(), data.end());
}