Is this a proper way to be naming files and making there file types?

Trying to learn how to deal with files and I wanted to make a way for the user to make his own file name and then I want it to be a .txt file, so I take the fileName variable after the user has created a name for it then add ".txt" for the file type then convert the string to a constant char for the open method. Is this a bad way of doing it? Thank you :P
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{

    ofstream fileObject; // ofstream object to read/write to and from file

    string fileName = ""; // The file name to be created
    cout << "Please create file name: "; std::getline(cin, fileName);
    fileName = fileName + ".txt"; // Makes file a .txt file
    const char* fileNameConst = fileName.c_str(); // converts string to const char for open()

    if (!fileObject.is_open())
    {
        fileObject.open(fileNameConst);
    }
    fileObject.close();
    return 0;
}
You're all good I think, altho you can just do this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{

    ofstream fileObject; // ofstream object to read/write to and from file

    string fileName = ""; // The file name to be created
    cout << "Please create file name: "; std::getline(cin, fileName);
    fileName = fileName + ".txt"; // Makes file a .txt file

    if (!fileObject.is_open())
    {
        fileObject.open(fileName.data()); // or you can use .c_str()
    }
    fileObject.close();
    return 0;
}
Thanks man! Really helps just learned something new. :)
Topic archived. No new replies allowed.