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

How to read a text file and store into an array without knowing the size?

本文关键字:文件 取文本 存储 数组 读取 情况下 不知道      更新时间:2023-10-16

我是新来的。

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

#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>库的解决方案?我可以尽可能大地增加数组的大小,但这似乎不是一个好的解决方案。

最简单的方法是只使用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();
}

使用std::basic_string:

#include <iostream>
#include <fstream>
#include <string>
int main(){
ifstream data;
std::string s = "";
data.open("test.txt");
while(data>>s);
data.close();
}

最简单的方法是对文件中的元素进行计数。然后分配正确的内存量。然后将数据复制到内存中。

#include <iterator>
#include <algorithm>
int main()
{
std::ifstream    data("test.txt");
std::size_t  count = std::distance(std::istream_iterator<int>(data),
std::istream_iterator<int>{});
data.fseek(0); // Post C++11 this works as expected in older version you
// will need to reset the flags as well.
int data = new int[count];
std::copy(std::istream_iterator<int>(data), std::istream_iterator<int>{},
data);
}

当数组太小时,您可以放大它。使用一个你认为最合适的尺寸,当给出更多数据时,只放大。

#include <iostream>
#include <fstream>
int main() {
std::ifstream data;
int size = 100;
int* a = new int[size];
int i = 0;
data.open("test.txt");
if (data.is_open()) // check if file is open
return -1;
while (data.peek() != EOF) {
if (i >= size) {
int old_size = size;
size *= 2; // double the size, or what ever. just make it bigger
int* new_array = new int[size]; // create new array with new size
std::copy(a, a + old_size, new_array); // copy data to new array
int* tmp1 = a; // assign old array to a tmp pointer, to not lose the memory
a = new_array; // assign the newly allocated memory to the pointer
delete[] a; a = nullptr; // delete the old memory
}
data >> a[i];
std::cout << a[i] << 'n';
i++;
}
data.close();
// after you don't need the data anymore; delete[]
delete[] a; a = nullptr;
return 0;
}

有一件事我很难学会,那就是永远不要使用using namespace std;。您打开了一个非常大的命名空间。如果你意外地定义了一个与std中的函数同名的函数,你会得到一个编译器错误,这很难得到,它是关于什么的。


另一个建议是,您真的应该看看std::vector和所有其他STL容器。它们会减轻很多疼痛。