Problem with setting filename using a string...
I want to use the string - filename , as the file name, but I can't get it to work...
How can I do this???
I would also want to add Input to the file, where it says File Info, how would I do this...
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
{
string filename;
cin >> filename;
cout << filename;
}
FILE * file = fopen("This is where I want my string name" , ".dat","w");
fprintf(file, "File Info");
fclose(file);
system ("PAUSE");
return 0;
}
Any info. would be helpful...
Re: Problem with setting filename using a string...
Use string's c_str() method.
Code:
fopen(filename.c_str( ), "w");
Re: Problem with setting filename using a string...
I get the error message: 'filename' undeclared [first use of this function]...
Re: Problem with setting filename using a string...
Quote:
Originally Posted by
Adobe Dharuma
I get the error message: 'filename' undeclared [first use of this function]...
Code:
int main()
{
{
string filename;
cin >> filename;
cout << filename;
}
FILE * file = fopen("This is where I want my string name" , ".dat","w");
fprintf(file, "File Info");
fclose(file);
system ("PAUSE");
return 0;
}
You're limiting its scope by using those braces. I don't see what purpose they serve here.
Re: Problem with setting filename using a string...
I also don't see the purpose of using fopen() when C++ provides the fstream (or more specifically, ofstream) class.
Code:
#include <fstream>
int main()
{
...
std::cout << "Enter filename: ";
std::cin >> filename;
std::ofstream ofs(filename.c_str());
ofs << "File Info";
...
}