I have a number of command line arguments for my int main() program which are used in my program.
I would like to pass these input arguments to the fstream blah.open("filename") member function in some manner such that the output file indicates which arguments were inputted. You may assume all the input arguments are doubles.
example below that i'd hoped at least let me pass a single letter- though it doesn't
I guess I don't really understand your problem. I ran this code and it created an output file with the name of my first argument with the text hello in the file.
Ah, well its good to know that I was only a dereference out! Cheers
However, really what I want to do is include more than just one letter in the filename. In particular I want doubles in the name.
Imagine I run my program with 4 arguments, 1 char, and 3 doubles:
./program H 1.0 2.0 3.0
I'd like to get a filename out which is something like
H_1.0_2.0_3.0.data
Currently I can't see any way of generalising the above beyond a single char (which is why I tried the char in the first place- to indicate that I have at least tried).
#include <fstream>
#include <sstream>
#include <iostream>
usingnamespace std;
int main( int argc, char* argv[])
{
// ofstream fileOut;
ostringstream fileName ;
for ( int i=1; i < argc ; ++i )
fileName << argv[i] << (i+1==argc?"":"_") ; //not sure what this second part is?
fileName << ".dat" ;
cout << fileName.str() ; //is this just meant to output the filename to the terminal?
ofstream fileOut(fileName.str()) ; // is this a constructor for specific use in conjunction with ostringstream? I thought the syntax was fileOut.open("name");
//but trying fileOut.open(fileName.str()); didn't work either?
fileOut<< "hello";
fileOut.close();
}
Line 17 - yes.
Line 19 - ofstream fileOut(fileName.str().c_str()); - C++11 fstreams have a constructor that works with std::string. Specifying the file name and open mode in the constructor is pretty much the same as default construction followed by an open.
Line 13: (i+1==argc?"":"_") is shorthand for (pseudocode:)
1 2 3 4
if ( i+1 == argc)
""else"_"
Functionally equivalent:
1 2 3 4
int i ;
for ( i=1; i<argc-1; ++i )
fileName << argv[i] << '_' ;
fileName << argv[i] ;
it just keeps the '_' from being appended on the last iteration of the for loop.
ofstream fileOut;
char* filename = argv[1];
strcat( filename, ".txt") ; // append .txt to the filename
fileOut.open(filename); // create output file with name = to first argument + .txt
fileOut << "hello"; // write some text to output file
multiple arguments to create a single file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main(int argc, char * argv[])
{
//use multiple arguments to create a file name - sample input argument list is F 1.0 2.0 3.0
ofstream fileOut;
char* filename = argv[1];
for( int i = 2; i < argc; i++ )
{
strcat (filename, argv[i]);
}
strcat (filename, ".txt"); // append .txt to the filename
fileOut.open(filename);
fileOut << "hello"; // write some text to output file