Arhuro Arhuro - 2 months ago 22
C++ Question

Input and Output files

I am attempting to create a new input text file and read the contents of it and write to my output file. Thing is I tried so many things, Can someone explain what I should do with my code. Anything I can change.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
string fileName,fileName2,text;
cout << "Please enter file name fo input: ";
getline(cin ,fileName);
cout << "Please enter file name for output: ";
getline(cin, fileName2);
ofstream output(fileName2,ios_base::app);
std::fstream inFile;
inFile.open(fileName, std::fstream::in | std::fstream::out | std::fstream::trunc);
getline(inFile, text);
while(inFile)
{
inFile >> text;
}
output << text;
output.close();
inFile.close();
return 0;
}

Answer

you should clean up input buffer because getline doesn't flush it for you. inFile.open(fileName, std::fstream::in | std::fstream::out | std::fstream::trunc); remove trunc because this flag clear the content of input file while opening it

your program should look like:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
 {
    string fileName, fileName2, text;

    cout << "Please enter file name fo input: ";
    getline(cin ,fileName);
    cin.ignore(1, '\n');

    cout << "Please enter file name for output: ";
    getline(cin, fileName2);
    cin.ignore(1, '\n');

    ofstream output(fileName2.c_str(), ios_base::app);

    std::fstream inFile;
    inFile.open(fileName.c_str(), std::ios::in);

    if(!inFile)
        cout << "Failed to open input file!" << endl;
    while(getline(inFile, text) )
    {
        output << text;
    }


    output.close();
    inFile.close();
    return 0;
 }
Comments