繁体   English   中英

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

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

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中读入,但是在文件上打开了一个ofstream ofstream仅允许您输出到文件,而不能从文件中读取文件,因此仅定义了<<运算符,而不是>> 您想在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)

您没有正确使用ifstreamofsteam ifstream用于读取, ofstream用于将内容写入文件。 但是,您的代码中还有更多问题,即

  • 使用未初始化的numbers数组
  • 使用未初始化的变量
  • 尝试访问array [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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM