It's pretty straightforward, just open an output file. If it doesn't exist then the program will attempt to create it.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char ch;
string fileName, fileContents;
ifstream readFile;
ofstream writeFile;
cout<<"Enter a file to create (ex. somefile.txt): ";
getline ( cin, fileName );
writeFile.open ( fileName.c_str() );
if ( writeFile.good () ) {
cout<<"File opened\nEnter a string to place in the file: ";
getline ( cin, fileContents );
writeFile<<fileContents;
writeFile.close();
cout<<"Would you like to view the file? (y/n): ";
if ( ( ch = cin.get() ) == 'y' ) {
readFile.open ( fileName.c_str() );
getline ( readFile, fileContents );
cout<<fileContents<<"\n";
readFile.close();
}
else if ( ch == 'n' )
cout<<"Have a nice day!\n";
else
cout<<"Invalid input\n";
}
else
cerr<<"File could not be opened\n";
return 0;
}
-Prelude