如何在不知道大小的情况下读取文本文件并存储到数组中?

问题描述 投票:0回答:2

我是新来的。

如何在不知道文本文件中数据数量的情况下读取文本文件并将其存储到数组中?

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    ifstream data;
    int a[100];
    int i=0;

    data.open("test.txt");
    while(data>>a[i]){
        cout << a[i] << endl;
        i++;
    }
    data.close();
}

在我的代码中,数组大小是固定的。有没有使用<vector>库的解决方案吗?我可以增加数组的大小,但是这似乎不是一个好的解决方案。

c++ arrays text-files
2个回答
0
投票

最简单的方法是只使用std::vector


如果您不愿意这样做,那么从概念上讲,您必须这样做

  1. 计数数据数:X
  2. 分配足够的内存来存储X数据项。

类似于以下内容的工作(注意:我没有测试代码)

#include <iostream>
#include <fstream>
using namespace std;

size_t data_size(const string name)
{
    size_t c = 0;
    ifstream data;
    data.open(name);

     while(data>>a[i])
        c++;

    data.close();
    return c;
}

int main(){
    string name = "test.txt"

    int* a = new int [data_size(name)] ;
    int i=0;

    ifstream data;
    data.open("test.txt");
    while(data>>a[i]){
        cout << a[i] << endl;
        i++;
    }
    data.close();
}

0
投票

使用std::basic_string及其append方法

© www.soinside.com 2019 - 2024. All rights reserved.