AvP*_*AvP 2 c++ file-io ifstream
我有一个任务,我应该读取包含整数的多个文件(每行一个),并在排序后将它们合并到输出文本文件中.我是C++的新手,所以我不知道一切是如何运作的.我用两个.txt文件测试我的程序.第一个文件名为fileone.txt,包含1,2,7(我不知道如何格式化它,但它们都在不同的行上.)第二个文件名为filetwo.txt,包含1,3,5, 9,10(同样每个整数都在不同的行上).
我编写了以下代码,打开两个文件并打印内容.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
ifstream iFile;
ifstream jFile;
iFile.open("fileone.txt");
jFile.open("filetwo.txt");
int int1 = 0;
int int2 = 0;
if (iFile.is_open() && jFile.is_open() ){
while (iFile.good() || jFile.good() ) {
iFile >> int1;
jFile >> int2;
cout << "From first file:" << int1 << endl;
cout << "From second file:" << int2 << endl;
}
}
iFile.close();
jFile.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个程序的输出是

我遇到的问题是第一个文件中的最后一个数字被多次打印.我想要的输出是在打印文件中的最后一个整数后停止打印.仅当第二个文件包含的整数多于第一个文件时,才会出现此问题.有没有办法在第一个文件到达结尾时停止打印,同时仍然打印第二个文件中的所有数字?
这样就可以了
while (iFile || jFile) {
if(iFile >> int1) // make sure the read succeeded!!
cout << "From first file:" << int1 << endl;
if(jFile >> int2) // make sure the read succeeded!!
cout << "From second file:" << int2 << endl;
}
Run Code Online (Sandbox Code Playgroud)
如果您检查是否已成功读取数据,则应该只使用数据.
| 归档时间: |
|
| 查看次数: |
721 次 |
| 最近记录: |