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>
usingnamespace std;
int main()
{
ofstream myfile;
// Allow User to Input Name of Goal
string goal_name, specific, measurable, attainable, realistic, special_day;
shortint 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");
#include <fstream>
#include <iostream>
#include <string>
usingnamespace 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;
}
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.