How to create a file with imputed file name?

I need to create a file with custom file name. Person has to imput the files name and then it is checked if it exists or not. After that it gives a response.

This is the code fragment:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char* bookID;
cout << "Enter book's ID:" << endl;
cin >> bookID;
ifstream f(bookID);
if(f.is_open()){
   cout << "The file already exist!" << endl;
}
else{
   ofstream of(bookID);
   of << "Author:" << endl;
   of << "Title:" << endl;
   cout << "New file have been created!" << endl;
   of.close();

}
f.close();


problems:
1. After everything is done the console crashes.
2. It creates .file and not .txt. I would prefer that it would be .txt, but if there is no other way then I could work with .file

I think it is somehow related to char*, but it is a requirement for ifstream and ofstream.
I been trying to find this solution but no luck so far.
Any suggestions?

Thanks in advance.
Last edited on
> char* bookID;
Yeah, you need to allocate some memory.

This is good.
char bookID[100];

This is better
std::string bookID;

> but it is a requirement for ifstream and ofstream.
So from a std::string, you would use the c_str() method.
ifstream f(bookID.c_str());

It's even better in C++11.
https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream
You can just use a std::string directly.


Thank you very much :)
Topic archived. No new replies allowed.