Search code examples
c++linuxg++ofstream

G++ compiler: cant write to file


So one day I made a small program to test out for a much bigger one that I was making on Visual Studio 2019 and here's what it looked like:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    string path;
    cout << "Enter path and filename: ";
    cin >> path;
    ofstream writer();
    writer.open(path);
    writer << "hi\n";
    writer.close();
    return 0;
}

but recently I've switched to Ubuntu and tried out my program but g++ threw this at me:

error: request for member ‘open’ in ‘writer’, which is of non-class type ‘std::ofstream() {aka std::basic_ofstream<char>()}’ writer.open(path);

error: invalid operands of types ‘std::ofstream() {aka std::basic_ofstream<char>()}’ and ‘const char [3]’ to binary ‘operator<<’ writer << "hi";

error: request for member ‘close’ in ‘writer’, which is of non-class type ‘std::ofstream() {aka std::basic_ofstream<char>()}’ writer.close();

I didn't really understand what was the problem because on Visual Studio it compiled just fine and ran without any problems so if anyone can help me and point me in the right direction I would appreciate it.


Solution

  • ofstream writer();
    

    This is wrong.

    You accidentally declared a function.

    Remove the ().

    (You must have been running different code under Visual Studio.)