-1

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

jww
  • 97,681
  • 90
  • 411
  • 885
Matt Swezey
  • 379
  • 3
  • 11
  • 27

3 Answers3

1

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
  • 31,821
  • 4
  • 39
  • 33
  • 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); – Matt Swezey Sep 12 '10 at 18:56
1

To change fileName extension:

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

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
  • 28,107
  • 9
  • 89
  • 113