[英]C++ reading from a text file into a array and then into another text file
integers.txt has the following numbers: 1 2 3 4 5 6 7 8 9 10 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;
}
I want the program to output the integers from integers.txt file to an array and from the array to in.txt file. 我希望程序将整数从integers.txt文件输出到数组,并从数组输出到in.txt文件。 I get the following error:
no match for 'operator>>' in 'outf >> numbers[10]'
我收到以下错误:
no match for 'operator>>' in 'outf >> numbers[10]'
You have swapped your file stream types. 您已交换文件流类型。
You want to read in from integers.txt, but you opened an ofstream
on the file. 您想从integers.txt中读入,但是在文件上打开了一个
ofstream
。 An ofstream
only lets you output to the file, not read from it, and therefore only has the <<
operator defined, not >>
. ofstream
仅允许您输出到文件,而不能从文件中读取文件,因此仅定义了<<
运算符,而不是>>
。 You want to open an ifstream
on integers.txt so that you can read input from the file, and probably open an ofstream
on in.txt. 您想在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)
You are not using ifstream
and ofsteam
correctly. 您没有正确使用
ifstream
和ofsteam
。 ifstream
is for reading and ofstream
is for writing the content to the file. ifstream
用于读取, ofstream
用于将内容写入文件。 However there are some more issues in your code ie 但是,您的代码中还有更多问题,即
numbers
numbers
数组 numbers[10]
) it gives an error that stack around the variable 'numbers' is corrupted
numbers[10]
)时,会给出错误,表明stack around the variable 'numbers' is corrupted
Following code will do the task for you: 以下代码将为您完成任务:
#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.