Trouble Writing To File

Jan 12, 2012 at 12:25am
I am having trouble getting my program to compile without errors. I will post my source and the error that I get. Any ideas on where I went wrong? I am still new to C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    string file;
    string text;
    cout << "File: ";
    cin >> file;
    cout << "Text: ";
    cin >> text;
    ofstream myfile;
    myfile.open(file);
    myfile << text;
    myfile.close;
    system("pause >nul");
    return 0;
}


1
2
3
13 C:\Users\Jake\Programming\C++\testfile.cpp no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)' 
 note C:\Dev-Cpp\include\c++\3.4.2\fstream:695 candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>] 
15 C:\Users\Jake\Programming\C++\testfile.cpp statement cannot resolve address of overloaded function  
Last edited on Jan 12, 2012 at 12:34am
Jan 12, 2012 at 12:35am
Before C++11 the open function only accept c-strings (const char*) so you have to convert the std::string into a c-string using the c_str() member function: myfile.open(file.c_str());

line 15 should be myfile.close();
Jan 12, 2012 at 12:38am
I see a few things that look like they will cause problems.

First of all seeing as you are using strings you should add #include <string> to the top of your file.

Second to close the file you use .close() not .fclose. (Which your second compiler error points out)

Finally the argument of myfile.open() needs to be a const char* not a string. To convert a string to the right format you need to use .c_str() at the end of it (Which is what the first error is saying).

Something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string> 
#include <fstream>

using namespace std;

int main() {
    string file;
    string text;

    cout << "File: ";
    cin >> file;
    cout << "Text: ";
    cin >> text;

    ofstream myfile;

    myfile.open(file.c_str());
    myfile << text;
    myfile.close();

    system("pause >nul");
    return 0;
}


I would also suggest trying to use different things than system() to pause your program as it is not cross platform and is much more work for the compiler to do. Try looking into cin.get() or similar ideas.

(Also too slow)~
Last edited on Jan 12, 2012 at 12:39am
Jan 12, 2012 at 12:50am
Thanks guys! I used your excellent advice and the program works now! :) That helped a lot, along with clearing up a few things.
Jan 12, 2012 at 6:38am
closed account (zvRX92yv)
std::cin.ignore() works well.
Last edited on Jan 12, 2012 at 6:39am
Topic archived. No new replies allowed.