【问题标题】:ostream .open function not existing (C++)ostream .open 函数不存在 (C++)
【发布时间】:2016-08-05 12:45:45
【问题描述】:

所以我是编程新手,我正在学习一个教程,我开始使用 fstream,但我不知道我的编译器是否表现得很奇怪,或者我缺少文件或其他东西,但 .open 函数确实如此似乎不起作用,fstream 的行为很奇怪。 (就像你不能使用(ostreamobject)(“test.txt”)一样;我是编程新手,所以请不要使用技术术语。

我搜索了一下,但没有找到任何东西。

我不知道我的代码或编译器出了什么问题,但 outputFile.open 的存在并不奇怪。我正在使用 Visual Studio 2015。这是我编写的少量代码,但仍然出现错误。代码如下:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ostream oFile;
istream iFile;

oFile.open("test.txt");

    return 0;
}

这是错误代码:

1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(13): 错误 C2512: 'std::basic_ostream>': 没有合适的默认构造函数可用 1> d:\programmering\vc\include\iosfwd(679): 注意:见'std::basic_ostream>'的声明 1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(14): 错误 C2512: 'std::basic_istream>': 没有合适的默认构造函数可用 1> d:\programmering\vc\include\iosfwd(678): 注意:见'std::basic_istream>'的声明 1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(16): error C2039: 'open': is not a member of 'std::basic_ostream>' 1> d:\programmering\vc\include\iosfwd(679): 注意:见'std::basic_ostream>'的声明 ========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========

【问题讨论】:

    标签: c++ fstream


    【解决方案1】:

    问题是,您使用的是“ost​​ream”和“istream”而不是“ofstream”和“ifstream”(注意“file")。

    使用这个版本:

    #include "stdafx.h"
    // #include <iostream> // you don't need this and it caused most of your confusion!
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
       ofstream oFile;
       ifstream iFile;
    
       oFile.open("test.txt");
    
       return 0;
    }
    

    仅供参考: “ofstream”和“ifstream”都是“ost​​ream”和“istream”的超类。它们提供了与文件交互的更多功能(如“打开”)

    【讨论】:

    • 非常感谢,我很笨:D
    【解决方案2】:

    嗯,它存在。没有采用文件名的 ostream 构造函数。

    你的意思是ofstream

    您可以通过简单地访问文档来检查这一点。

    如果你的教程真的是 ostream,请告诉我们它是什么并停止使用它。
    您应该从a good book 学习 C++,而不是从互联网上的随机“tuts”学习。

    【讨论】:

      【解决方案3】:

      考虑将 oFile 和 iFile 声明为具体文件。

      ofstream oFile;
      ifstream iFile;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-27
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        相关资源
        最近更新 更多