What I would like is when I input the file path in the console window (lets say C:\hello.txt), I would like it to create, open, then write text into the file. Here's an example of my code.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  string test;
  
  cin >> test;
  
  ofstream myfile;
  myfile.open (test);
  myfile << "Test\n";
  myfile.close();
  return 0;
}

If you want help, you need to explain the problem and actually ask a question.

myfile.open (test);

Normally myfile.open supports strings, so i need to declare a text file like this

myfile.open ("test.txt");

But I want it so if i type in lets say example.txt in the console window, it create/opens then writes into the file of what i've typed.

try this

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main( )
{
char* test;
cin.getline(test, 256, '\n');// note: use cin.getline( ) for getting string inputs
string Stest(test);
ofstream myfile(Stest.c_str( ));//myfile.open( ) does not create new file
myfile << "Test\n";
myfile.flush( );//needed for the file to be created
myfile.close( );

return 0;
}

This is how you do it, a very basic and simple example:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
	string test;
	ofstream myfile;

	cout << "Please enter text: ";
	cin >> test;
 
	myfile.open ("test.txt");
	myfile << test;
	myfile.close();

	return 0;
}

If you want to get the file name from the user and then open that file do this

#include <string>
#include <iostream>
#include <fstream>

using std::string;
using std::cout;
using std::cin;
using std::ofstream;

int main()
{
    string filename;
    cout << "Please enter the filename: ";
    cin >> filename;
    ofstream fout(filename.c_str());  // use the c_str() function to return a const char *
    //... rest of your code here
}

Thanks Cross!

But how would i:

myfile.open (test); //my input from cin

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.