Username as directory name

1
2
3
4
CreateDirectory("c:\\u", NULL);
cout << "Enter Username : " << endl;
cin >> username;
CreateDirectory("c:\\u\\"username"", NULL);

Clearly that code does not work. How can I make a directory using the user inputted information?
1
2
3
4
5
6
string username;
cin >> username;

string path = "C:/u/" + username;

CreateDirectoryA(path.c_str(), NULL);


A few things to note:

1) '/' for directory separator instead of '\\' (easier, less error prone, more portable, better habit to get into)
2) CreateDirectoryA instead of CreateDirectory (because we have a char string and not a TCHAR string)

For more on point #2, see this:
http://cplusplus.com/forum/articles/16820/
Last edited on
Very nice! If I change that I will have to change
1
2
ofstream myfile;
myfile.open ("C:/u/"...".txt");

I don't know how to make that work, can I have some help with that? Plus I thought C++ did not read /, that's why I changed to \\. Are they both accepted then??
If I change that I will have to change


It's the same thing. Just build your full string in a string, then call c_str:

1
2
string filename = "C:/u/" + whatever + ".txt";
myfile.open( filename.c_str() );



Plus I thought C++ did not read /, that's why I changed to \\. Are they both accepted then??


It's not a C++ thing as much as it's an API thing.

And yes, both / and \\ are accepted as directory separators on Windows, but only / is accepted on other platforms (hence why / should be preferred)
Topic archived. No new replies allowed.