C++从ifstream创建一个可变大小的数组

C++ Creating a variable sized array from ifstream

本文关键字:数组 一个 ifstream 创建 C++      更新时间:2023-10-16

请注意:我的c++编程技能和术语充其量只是中等水平。所以请温柔一点;)。

我正在为一个大学班级研究一个多排序算法。最初,我构建了一个包含20个整数的数组的程序,因为它和.txt文件一样大。最后一个实验室现在要求接收10、100、1000、10000、100000和1000000个不同数字的文件。我最初在for循环中使用ifstream来读取int。现在我需要从文件中读取可变数量的int,我遇到了这段代码的问题。我已经广泛搜索了这个网站和谷歌,以找到这个问题的答案。我尝试了几十个不同的代码片段,但都没有成功。这是我目前正在运行的代码,适用于20 int。

int i;
int A[20];
int length;
char unsortedFilename[200];
ifstream unsorted;
cout << "Please type the full name of the file you would like sorted.n* ";
cin >> unsortedFilename;
unsorted.open(unsortedFilename);
length = (sizeof(A) / sizeof(*A));
for( i = 0; i < length; i++ )
{
    unsorted >> A[i];
    cout << A[i] << "n";
}
insertionSort();

我确实有其他代码混合在其中,但它是错误检查、删除重复编号的选择等。我希望这样的代码可以运行"I"多次,其中"I"实际上是文件中的int数。另外,正如我前面提到的,我需要输入一个包含1000000个数字的文件。我不相信int数组能够容纳那么多数字。这会像把我所有的int换成long一样容易吗?

谢谢你能提供的任何帮助。

  1. 如注释中所建议的,使用std::vector<int>而不是数组。

  2. 使用while循环而不是for循环。当没有可读取的数字时,中断while循环。

while循环:

std::vector<int> A;
int item;
while ( unsorted >> item )
{
   A.push_back(item);
}

您可以使用std::vector::iteratorstd::vector进行排序,也可以简单地通过A.data()返回的int*访问数据。

您可以简单地将所有数字读入一个向量。然后使用向量,就像使用数组一样。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main()
{
  std::string unsortedFilename;
  std::cout << "Please type the full name of the file you would like sorted.n";
  std::cin >> unsortedFilename;
  std::ifstream is(unsortedFilename);
  std::istream_iterator<int> start(is), end;
  std::vector<int> A(start, end);
  std::cout << "Read " << A.size() << " numbers" << std::endl;
}

您想要的是一个向量。

试试这个,

int i;
vector<int> A;
int length;
string unsortedFilename;
ifstream unsorted;
cout << "Please type the full name of the file you would like sorted.n* ";
cin >> unsortedFilename;
unsorted.open(unsortedFilename);
int temp;
for( i = 0; unsorted >> temp; i++ )
{
    A.push_back(temp);
    cout << A[i] << "n";
}
insertionSort();

向量基本上是一个动态数组。它会随着需要更多空间而自动增长。这样,无论你有10件、100件甚至100000件物品,它都会自动为你增长。

文件名也要使用字符串,有些文件名的长度超过200个字符。

祝你好运!

需要输入一个包含1000000个数字的文件。我不相信int数组能够容纳那么多数字。

当然可以。100万int是大约4Mb的内存,这是一个微不足道的数量。您甚至可以像现在int A[1000000];一样将其声明为静态。

但真正的问题是,您在代码中假设了一个固定的长度,而不是根据输入来确定长度。我想这就是你的作业要教你的,所以我不会给你看解决方案。但是考虑使用ifstream::eof,并使您的排序接受长度作为参数。。。

相关文章: