c++从一个文本文件读入数组,然后读入另一个文本文件

C++ reading from a text file into a array and then into another text file

本文关键字:文件 文本 数组 然后 另一个 一个 c++      更新时间:2023-10-16

integers.txt中有如下数字:1 2 3 4 5 6 7 8 9 10

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  int numbers[10];
  int i;
  ofstream outf;
  outf.open("integers.txt");
  ifstream inf;
  inf.open("in.txt");
  for(int i = 0; i < numbers[i]; i++);
  {
    outf >> numbers[10];
  }
  inf << numbers[10];
  outf.close();
  inf.close();
  return 0;
}

我想让程序从integers.txt文件输出到数组,从数组输出到in.txt文件。我得到以下错误:no match for 'operator>>' in 'outf >> numbers[10]'

您已经交换了文件流类型。

您想从integers.txt中读取数据,但是您在该文件上打开了一个ofstreamofstream只允许您向文件输出,而不是从中读取,因此只定义了<<操作符,而不是>>。您希望在integers.txt上打开ifstream,以便您可以从文件中读取输入,并且可能在in.txt上打开ofstream

ifstream inf;
inf.open("integers.txt");
ofstream outf;
outf.open("in.txt")
//read in from inf (aka integers.txt)
//output to outf (aka in.txt)

您没有正确使用ifstreamofsteamifstream用于读取,ofstream用于将内容写入文件。然而,在你的代码中有一些更多的问题,即

  • 使用未初始化的numbers数组
  • 使用未初始化的变量i
  • 尝试访问数组[size] (numbers[10])它给出了一个错误,stack around the variable 'numbers' is corrupted

下面的代码将为您完成任务:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  int numbers[10] = {0};
  int i = 0;
  ofstream outf;
  outf.open("in.txt");
  ifstream inf;
  inf.open("integers.txt");
  while (inf >> numbers[i])
  {
    inf >> numbers[i];
    outf << " " << numbers[i];
    i++;
  }
  outf.close();
  inf.close();
  return 0;
}