【问题标题】:G++ compiler: cant write to file [duplicate]G ++编译器:无法写入文件[重复]
【发布时间】:2020-06-10 19:31:05
【问题描述】:

所以有一天我做了一个小程序来测试我在 Visual Studio 2019 上制作的一个更大的程序,它看起来像这样:

#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;
}

但最近我切换到 Ubuntu 并尝试了我的程序,但 g++ 向我抛出了这个:

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();

我真的不明白问题出在哪里,因为在 Visual Studio 上它编译得很好并且运行没有任何问题,所以如果有人可以帮助我并指出正确的方向,我将不胜感激。

【问题讨论】:

    标签: c++ linux g++ ofstream


    【解决方案1】:
    ofstream writer();
    

    这是错误的。

    你不小心声明了一个函数。

    删除()

    (你肯定在 Visual Studio 下运行过不同的代码。)

    【讨论】:

    • 不知道VS19发生了什么。
    • @cigien OP 想象中的
    • 你应该在答案中这么说。好吧,换句话说:)
    • 好吧,好像我忘了说“编译得很好”我会编辑它
    • @cppiscool 编辑它没有意义;那是不可能的。您必须运行或编译过不同的代码。
    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多