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)
您没有正确使用ifstream
和ofsteam
。ifstream
用于读取,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;
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)