Search code examples
c++filenamesistream

Simple user request for filename for output and input


How can I request the user to input the filename that my program needs to read from and have it output the name with .out extension instead?

Example:

char fileName[256];
cout << "What is the file name that should be processed?";
cin >> fileName;

inFile.open(fileName);
outFile.open(fileName);

But I need it to save the file as a filename.out instead of the original document type (IE:.txt)

I've tried this:

char fileName[256];
cout << "What is the file name that should be processed?";
cin >> fileName;

inFile.open(fileName.txt);
outFile.open(fileName.out);

But I get these errors:

c:\users\matt\documents\visual studio 2008\projects\dspi\dspi\dspi.cpp(41) : error C2228: left of '.txt' must have class/struct/union 1> type is 'char [256]'

c:\users\matt\documents\visual studio 2008\projects\dspi\dspi\dspi.cpp(42) : error C2228: left of '.out' must have class/struct/union 1> type is 'char [256]'


Solution

  • To change fileName extension:

    string fileName;
    cin >> fileName;
    string newFileName = fileName.substr(0, fileName.find_last_of('.')) + ".out";