没有从以下输入获取输出.txt文件

时间:2013-09-07 19:22:10

标签: c++ io

我试图从目录路径的输入中获取两个给定的文本文件,获取它们的整数,然后将这些整数输出到" merged"文本文件。我是来自Java的C ++新手,所以到目前为止这已经非常棘手了。这段代码构建并运行,但我实际上并没有得到输出文件。有什么帮助吗?

编辑:

我有合并的文件,但我似乎无法将data1和data2按升序排序,因为它们已在输出文件中实现了" merge.txt" 。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void textMerge(){
    ifstream inFile1;
    ifstream inFile2;
    string inputFileName1;
    string inputFileName2;
    ofstream outputFile("merge.txt");
    cout << "1. Please enter the directory path of the first text list: " << endl;    // Open first file based on given directory path
    cin >> inputFileName1;
    inFile1.open(inputFileName1);
    cout << "2. Please enter the directory path of the second text list: " << endl;  // Repeat open file for second directory path
    cin >> inputFileName2;
    inFile2.open(inputFileName2);
    if (inFile1.is_open() && inFile2.is_open()){
    int data1;
    int data2;
    while(!inFile1.eof() && !inFile2.eof()){                // while both files haven't reached end-of-file yet
        inFile1 >> data1;        // get next number for first file
        inFile2 >> data2;
                                 // get next number for second file
        outputFile << data1 << data2;     // output each integer from files 1 and 2 to outputFile(merge.txt)
    }
    inFile1.close();
    inFile2.close();
    outputFile.close();
    } 
    else{
        cerr << "The file(s) failed to open properly.";
        exit(0);
    }
}
int main(){
    textMerge();
}

2 个答案:

答案 0 :(得分:0)

您的代码没有任何问题。可能出错的是运行程序时使用的文件名。请务必提供完整的文件名(包括路径)。

答案 1 :(得分:0)

我想知道你为什么要包含vector标题,但是除此之外,你应该将整个路径作为输入而不是绝对路径。同时将你的状态改为

while(inFile1>>data1 && inFile2>>data2)

检查读取变量是否成功,而不是文件是否已经结束。