Building a path / filename string and using it as a ofstream fout argument
May 17, 2010 at 5:02pm UTC
Yeah, so the title says it all.
I can't figure out the syntax. The idea is that it prompts the user for a filename and destination, builds the string (str) and puts that for the ofstream fout argument.
I know that the path has to have double quotes around it, I'm not sure how to do this because I'm new and don't know how to do anything.
Any help would be greatly appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main () {
string filename, filedir, str;
cout << "Enter a file name and press ENTER: " ;
getline(cin, filename); //Get filename
filename = filename + ".txt" ; //Append .txt
cout << filename << endl;
cout << "Enter a file location and press ENTER: " ;
getline(cin, filedir); //Get file location
filedir = filedir + "/" ; //append / to end of location
cout << filedir << endl;
str = filedir + filename;
cout << str <<endl;
ofstream fout(str);
fout << "This is a line of text" ;
return 0;
}
May 17, 2010 at 7:46pm UTC
I know that the path has to have double quotes around it
No, that's only when you want to pass a command line argument with spaces. Filenames for std::fstream objects don't need any special characters.
Pass str.c_str() to the constructor.
May 17, 2010 at 8:34pm UTC
Thanks Helios. Knew I was missing something. :)
The book I'm working through neglects to mention that. Although C++ Without Fear has proven an excellent guide.
Glad there are fellow geeks willing to put in time for a newbie.
Topic archived. No new replies allowed.