使用ifstream从文本文件打印整数 [英] Using ifstream to print integers from text files

查看:128
本文介绍了使用ifstream从文本文件打印整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个赋值,我应该读取包含整数(每行一个)的多个文件,并将其排序后合并到一个输出文本文件。我是新的C ++,所以我不知道一切如何工作。我用两个.txt文件测试我的程序。第一个文件称为fileone.txt,包含1,2,7(我不知道如何格式化,但他们都在不同的行。)第二个文件称为filetwo.txt,并包含1,3,5,

I have an assignment where I am supposed to read multiple files containing integers (one on each line) and merge them into a output text file after sorting them. I am new to C++ so I do not know how everything works. I am testing my program with two .txt files. The first file is called fileone.txt, contains 1,2,7 (I do not know how to format this but they are all on different lines.) The second file is called filetwo.txt, and contains 1,3,5,9,10 (again every integer is on a different line).

我写了以下代码打开这两个文件并打印内容。

I have written the following code which opens both files and prints the contents.

#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;
}

这个程序的输出是

The output of this program is

我遇到的问题是第一个文件被打印多次。我想要的输出是从文件打印最后一个整数后停止打印。仅当第二个文件包含比第一个文件多的整数时,才会出现此问题。是否有办法在第一个文件到达结束时停止打印,并仍然打印第二个文件中的所有数字?

The problem I am having is the last number in the first file gets printed multiple times. The output I want is to stop printing after printing the last integer from the file. The problem only appears when the second file contains more integers than the first one. Is there a way to stop printing from the first file when it reaches the end and while still print all the numbers from the second file?

推荐答案

这将会做的

   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;
    }

如果您检查是否已成功读取, 。

You should only really use data if you checked to see if it was successfully read.

这篇关于使用ifstream从文本文件打印整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆