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

时间:2014-10-28 18:06:24

标签: c++

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

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

如果有帮助,您可以找到data.txt here。样品:

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;
    }
}

2 个答案:

答案 0 :(得分:2)

要向数组添加更多元素,超出其容量,您必须:

  1. 分配一个更大的新阵列。
  2. 将所有元素从旧数组复制到新数组。
  3. 删除旧数组。
  4. 追加新元素。
  5. 更安全的解决方案是使用std::vectorpush_back方法。

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

答案 1 :(得分:0)

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

#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(""
        "600000\n"
        "523887 283708\n"
        "231749 419866\n"
        "293707 273512\n"
        "296065 215334\n"
        "233447 207124\n"
        "264381 460210\n"
        "374915 262848\n"
        "449017 329022\n"
        "374111 151212\n"
        "2933 496970\n");
    // 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());
}
相关问题