views:

42

answers:

3

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" 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]'

+1  A: 

You are using iostreams, implying the use of C++. That in turn means you should probably be using std::string, which has overloaded operators for string concatenation - and the nice side effect of automatic memory management and added security.

#include <string>
// ...
// ...
std::string input_filename;
std::cout << "What is the file name that should be processed?\n";
std::cin >> input_filename;
// ...
infile.open(input_filename + ".txt");
Jim Brissom
I tried that but got an error. Looked it up and .open doesn't take string as an argument. But I found a line of code that makes it so. inFile.open(inputFile.c_str(), ios::in); outFile.open(outputFile.c_str(), ios::in);
MOneAtt
A: 

Writing filename.txt implies that fileName is an object and you want to access it's data member .txt. (Similar argument applies to fileName.out). Instead, use

inFile.open(fileName + ".txt");
outFile.open(fileName + ".out");
Michael Mior
Yeah, now that i think about it that makes perfect logical sense!
MOneAtt
+1  A: 

To change fileName extension:

string fileName;
cin >> fileName;
string newFileName = fileName.substr(0, fileName.find_last_of('.')) + ".out";
Denis
Try testing with a file name like 'x.y.z', or path like: "abc.def\xyz\file.txt".
Jerry Coffin
That was supposed to be find_last_of, not find_first_of :) Thanks for pointing out my mistake.
Denis
Thanks! Worked like a charm!
MOneAtt