cout << "Enter your full name";
char* name ;
cin >> name;
if( _mkdir("c:\\names") == 0 ) {
cout << "directory successfully created";
} else {
cout << "there was a problem creating 开发者_Go百科a directory";
}
Now i want to create a file ( a .txt file ) in the directory names
with the same name as the name of the user
. I mean the name which the user entered during cin >> name;
.
How can i do this ?
ofstream writeName( "c:/names/????);
----> PROBLEM
Use std::string
instead of char*
. As it is your code has Undefined Behavior. Use std::getline
instead of >>
. With >>
only the first whitespace-separated "word" is input. Then, compose the full path in a std::string
. The standard string class supports concatenation, so this should be easy.
Say, if that string is path
,
std::ofstream f( path.c_str() );
Cheers & hth.,
You can create a text file by fopen
ing the file or with ofstream
.
But your way of taking input for name
seems wrong. You didn't allocate space for name
. Try using malloc
or new
The char*
points to one char. Since it is not initialized it points to nirvana -> undefined bahavior.
You can try to use char name[MAX_LENGTH_FOR_YOUR_NAME]
. It's better to use a std::string name
here.
精彩评论