Changable filename based on user input

Good Morning

small question and thanks for your time

im trying to write a portion of this program so that the user can input the

name of a specific goal and then it creates a text file with that name.

however for 2 days of trying to find my answer all i can find for this is it

must be a constant char. can anyone point me in a direction of how make a file

whose name doesn't have to be constant

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

using namespace std;

int main()
{
    ofstream myfile;
    // Allow User to Input Name of Goal
    string goal_name, specific, measurable, attainable, realistic, special_day;
    short int year;
    char month, day;
    cout <<"please input a goal name"<<endl;
    getline (cin, goal_name);
    // Names the file after the goal name
    // *yes that is a failed attempt to make this work*
    myfile.open ("<<goal_name<<.txt");


thanks for your time,

wasing
So easy you'll be amazed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
  {
  ofstream f;
  string filename;

  cout << "Please enter a file name to write: ";
  getline( cin, filename );

  f.open( filename.c_str() );
  f << "Hello world!\n";
  f.close();

  cout << "Good job! 'type' or 'cat' your new file to see what it says.\n";
  return 0;
  }

Hope this help.s
wow thanks a million Duoas

is this referenced anywhere on this site because i would not have found that on my own.

anyway thanks again
Hi,


The problem is that a string type is being used here.

If I am not mistaken, the string type does not have a null character at the end and this is what gives you the problem.

Your filename, (goalname), mustn't be passed through as a string. The c_str() function can be used, (you can find a proper explanation to this function on the net).
Otherwise you can change your variable it from a string to a char array.

Hope this helps


daveD
Please do not give bad advice.
Using a std::string and the c_str() member function is exactly the correct thing to do.
I'd like to add an extension to Duoas' program at line 13, as the OP appeared to wanted to append .txt to the name.
goalname += ".txt";

-Albatross
hey thanks albatross i was wondering that earlier

thanks for all your help guys
Topic archived. No new replies allowed.