Errors when creating files.

I've been trying to have my program take the text entered by the user, save it as a variable, then create a file with the variable as the name of the file. I was going to post my progress so far to help show what I mean but I lost the file. The format of the file is .txt.


Thanks In Advance!!
Last edited on
Its only about 4 or 5 lines of code. Why don't you have another crack at it and post it here?
Okay, this is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>

int main()
{
string text;
ofstream file;
cout << "Please enter a new file name:\n";
cin >> text;
file.open(text)
}
Last edited on
Okay.

You need to prefix your standard library symbols with std::

Also the function open() requires a const char* rather than a std::string. You can get this using the c_str() member function of the std::string. This should work better:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string text;
    std::ofstream file;
    std::cout << "Please enter a new file name:\n";
    std::cin >> text;
    file.open(text.c_str());
}
Last edited on
THANK YOU SO MUCH!!!
I've been looking for the answer to this question for weeks!!

Also, couldn't you just put using namespace std; at the top?
You can use using namespace std; but it is greatly discouraged. It is okay for little noddy programs like this but it should not be used in any serious software.

http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
Thanks, one last question I can't figure out why this won't work:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main()
{
goto second;
}
int second()
{
 cout << "It worked!!";   
}
Don't use goto.

If you want to call a function you have to declare the function before you use it. And then to call it you simply use its name and append parentheses ().

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int second() // declare and define function
{
    cout << "It worked!!";   
}

int main()
{
    second(); // call function
}
Thanks!!!
Topic archived. No new replies allowed.