如何从文本文件中加载一堆数组元素?

时间:2018-03-27 17:52:31

标签: c++

如何在C ++中从文本文件加载数组。

我无法从文件中获取所有数组元素。

这是我的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main()
{

    ifstream file("file.txt");
    if(file.is_open())
        string myArray[5];

}

2 个答案:

答案 0 :(得分:0)

从文件中读取时,建议使用动态容器,例如std::vector

std::vector<int> database;
int number;
ifstream data_file("file.txt");
while (data_file >> number)
{
  database.push_back(number);
}

无论数量如何,上述片段都会读取文件中的整数。

阵列

数组的问题是您需要在声明数组之前知道数量。

const size_t capacity = 16;
int array[capacity];
for (unsigned int i = 0; i < capacity; ++i)
{
  data_file >> array[i];
};

上述片段假定文件中至少有16个数字。

答案 1 :(得分:0)

你将使计数器继续计数数据,直到你停止从文件中读取然后打开一个数组它的大小=这个计数器,然后打开新计数器说把fisrt数放在数组的第一个索引中这是代码

        int i=0 , j=0 ;
    ifstream file("statfile.txt") ;

    while(file >> data) {i++ ;}
    double arr[i];
    file.close();

    ifstream newfile("statfile.txt");
    while(newfile >> arr[j]) {j++ ;}
    for(j=0 ; j<i ; j++) {cout << arr[j] << " " ;}
相关问题