嗨我正在研究读取两个文件的程序,并且想要在各自的列中显示文件内容为前。如何在一个文件中读取并垂直显示内容,然后在另一个文件中读取并在C++中垂直显示内容
File1 File2
Time data Time data
我不会退出知道如何创建这样的列,我已经有了代码中的文件读取和执行功能所需要的,我难倒输出。如果任何人有任何建议或帮助将是非常棒的。谢谢! PS。这不是家庭作业相关。
嗨我正在研究读取两个文件的程序,并且想要在各自的列中显示文件内容为前。如何在一个文件中读取并垂直显示内容,然后在另一个文件中读取并在C++中垂直显示内容
File1 File2
Time data Time data
我不会退出知道如何创建这样的列,我已经有了代码中的文件读取和执行功能所需要的,我难倒输出。如果任何人有任何建议或帮助将是非常棒的。谢谢! PS。这不是家庭作业相关。
我会做这样的事情:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
int readLines(const std::string& fileName1, const std::string& fileName2)
{
string line1;
string line2;
ifstream file1 (fileName1.c_str());
ifstream file2 (fileName2.c_str());
if (file1.is_open() && file2.is_open())
{
cout << setw(20) << left << "File1" << "File2" << endl;
bool done;
done = file1.eof() && file2.eof();
while (!done)
{
getline (file1, line1);
getline (file2, line2);
line1.erase(std::remove(line1.begin(), line1.end(), '\n'), line1.end());
line2.erase(std::remove(line2.begin(), line2.end(), '\n'), line2.end());
cout << setw(20) << left << (file1.eof() ? "" : line1) << (file2.eof() ? "" : line2) << endl;
done = file1.eof() && file2.eof();
}
file1.close();
file2.close();
}
else
{
cout << "Unable to open some file";
}
return 0;
}
int main()
{
std::string fileName1("example1.txt");
std::string fileName2("example2.txt");
readLines(fileName1, fileName2);
return 0;
}
哦,这更像是我在找什么!谢谢! – Cka91405
这真的取决于你打算用什么工具?
你可以用“诅咒”的某些版本(与控制台的操作功能,如“去到这个位置”,“打印文本库在绿色“等),然后只要你喜欢绕着屏幕走动。
或者您可以将文件读入单独的变量,然后从循环中的每个文件打印。这不需要特别的编码。只需使用数组或向量来表示文件本身以及从中读取的数据。
事情是这样的:
const int nfiles = 2;
const char *filenames[nfiles] = { "file1.txt", "file2.txt" };
ifstream files[nfiles];
for(int i = 0; i < nfiles; i++)
{
if (!files[i].open(filenames[i]))
{
cerr << "Couldn't open file " << filenames[i] << endl;
exit(1);
}
}
bool done = false;
while(!done)
{
int errs = 0;
std::string data[nfiles];
for(int i = i < nfiles; i++)
{
if (!(files[i] >> data[i]))
{
errs++;
data[i] = "No data";
}
}
if (errs == nfiles)
{
done = true;
}
else
{
for(int i = 0; i < nfiles; i++)
{
... display data here ...
}
}
}
一种可能的方式是不是想编写一个文件,然后回去和写其他的。而是交错它们。写第一个文件的第一行,然后写第二个文件的第一行。然后新线等。 – 2013-04-03 13:53:46