I have a program that takes in the name of a file as an argument (example: books.txt), runs, and then outputs the results to a new text file. I need to name the output file with an addendum (example: books_output.txt).
The method that I tried was
ofstream outputFile;
outputFile.open(argv[1] + "_output.txt", ofstream::out);
but this didn't compile. How can I make this work?
Your statement should look like this (as mentioned in my comment):
outputFile.open(std::string(argv[1]) + "_output.txt", ofstream::out);
// ^^^^^^^^^^^^ ^
assumed argv[1]
comes from the standard main()
signature
int main(int argc, char* argv[])
argv[1]
is a char*
pointer and you can't concatenate char*
pointers that way.
As some people bother regarding support of obsolete C++ standard versions, the std::ofstream::open()
signatures of earlier versions didn't support a const std::string
parameter directly, but only const char*
. In case you have that situation your statement should look like
outputFile.open((std::string(argv[1]) + "_output.txt").c_str(), ofstream::out);