|
-
May 4th, 2009, 03:56 PM
#1
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...
-
May 4th, 2009, 04:38 PM
#2
Re: Problem with setting filename using a string...
Use string's c_str() method.
Code:
fopen(filename.c_str( ), "w");
-
May 4th, 2009, 04:52 PM
#3
Re: Problem with setting filename using a string...
I get the error message: 'filename' undeclared [first use of this function]...
-
May 4th, 2009, 06:47 PM
#4
Re: Problem with setting filename using a string...
 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.
-
May 4th, 2009, 07:32 PM
#5
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";
...
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|