用C ++读取一个巨大的文本文件

时间:2015-04-05 12:02:52

标签: c++ text text-files

现在,我想读一个文本文件,它的浮动数非常多,我不知道它有多少。我使用这段代码:

#‎include‬ "stdafx.h"
#include <iostream> 
#include <fstream> 

using namespace std;
int main()
{
    double a[391001];
    ifstream fg ("fg.txt");
    if (! fg.is_open())
    {
        cout << "Don't open file";
        return 0;
    } else {
        for (int i = 1; i <= 391000; i++)
        {
            fg >> a[i];
        }
    }
    for (int i =1; i <= 391000; i++)
    {
        cout << a[i] << " ";
    }
    fg.close();
    system("pause");
    return 0;
}

但它是循环

那么,你能告诉我怎么读吗?谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

#include <iostream>
#include <fstream>
#include <vector>

int main(int argc, char* argv[])
{
    std::vector<double> numbers;
    double buffer;
    std::ifstream in_file("doubles.txt"); //this is a placeholder, change it to the actual file name
    if(in_file.is_open()){
        while(in_file >> buffer){
            numbers.push_back(buffer);
        }
    }
    for(int i = 0; i < numbers.size(); ++i){
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}