读入两个文本文件,然后将它们组合在一起
reading in two text files and then combining them
我在编译我编写的代码时遇到了问题。这段代码旨在读取两个文本文件,然后输出这两个文件中的行。然后,我希望能够放置两个文件并将它们组合在一起,但第一行是file1文本,第二行是file2文本。
这是我的代码:
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
std::ifstream file1("file1.txt");
std::ifstream file2("file2.txt");
//std::ofstream combinedfile("combinedfile.txt");
//combinedfile << file1.rdbuf() << file2.rdbuf();
char filename[400];
string line;
string line2;
cout << "Enter name of file 1(including .txt): ";
cin >> filename;
file1.open(filename);
cout << "Enter name of file 2 (including .txt): ";
cin >> filename;
file2.open(filename);
if (file1.is_open())
{
while (file1.good() )
{
getline (filename,line);
cout << line << endl;
}
file1.close();
}
else cout << "Unable to open file";
return 0;
}
if (file2.is_open())
{
while (file2.good() )
{
getline (filename,line);
cout << line << endl;
}
file2.close();
}
else cout << "Unable to open file";
return 0;}
首先,不要执行while (file.good())
或while (!file.eof())
,它不会按预期工作。相反,喜欢while (std::getline(...))
。
如果你想阅读和打印交替的行,有两种可能的方法:
- 将这两个文件读取到两个
std::vector
对象中,并从这些矢量中进行打印。或者可能将两个矢量合并为一个矢量,然后打印出来 - 从第一个文件读取一行并打印,然后从第二个文件读取并打印,循环打印
第一种选择可能是最简单的,但使用的内存最多。
对于第二种选择,你可以这样做:
std::ifstream file1("file1.txt");
std::ifstream file2("file2.txt");
if (!file1 || !file2)
{
std::cout << "Error opening file " << (file1 ? 2 : 1) << ": " << strerror(errno) << 'n';
return 1;
}
do
{
std::string line;
if (std::getline(file1, line))
std::cout << line;
if (std::getline(file2, line))
std::cout << line;
} while (file1 || file2);
或者简单地说:
cout << ifstream(filename1, ios::in | ios::binary).rdbuf();
cout << ifstream(filename2, ios::in | ios::binary).rdbuf();
您的第二个if语句在main()-函数之外。在第一次返回0之后;关闭main()函数。代码中的另一个问题是,如果第二个if语句在main()-函数中,那么它永远不会到达,因为返回0;结束main()。我想,如果第一个文件流是"坏的",您只想执行return,所以您需要一个其他文件流的作用域;
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 将图形属性与 std::unique_ptr 捆绑在一起
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 按单词搜索文件,然后在C++中打印特定行数
- 如何在线程中初始化对象,然后在其他地方使用它?
- 在 c++ 中运行命令,然后在该程序中运行命令
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 为什么push_back和emplace_back结合在一起时,会有不同的行为
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 将两个矩阵组合在一起,然后用一个值组织另一个值
- 如何渲染成不同的层,然后将它们与OpenGL组合在一起
- 读入两个文本文件,然后将它们组合在一起
- 分别创建目标文件,然后在Makefile中将它们链接在一起的目的是什么?< / h1 >
- 如何将随机数组值一起添加到另一个数组中,然后在计算出现的值时显示它们?C++