【问题标题】:c++ ifstream to char *c++ ifstream转char *
【发布时间】:2011-08-23 01:57:16
【问题描述】:

我的代码用 ifstream 读取一个文件并解析它,现在我改变了一些东西,我不需要读取文件,因为是从另一个地方读取的,所以我有一个 char* 而不是 ifstream...如何更改使用 ifstream.get() 的代码? 再次感谢

【问题讨论】:

    标签: c++ string pointers char ifstream


    【解决方案1】:

    您只需将您的char * 放入std::stringstream

    std::stringstream buffer(your_string);
    

    然后您可以像使用std::ifstream 一样使用buffer(您无法打开或关闭它)。理想情况下,您的 parse-method 将引用 std::istream 作为参数,然后它不会介意它接收什么样的输入流:

    void parse(std::istream & input);
    

    由于std::ifstreamstd::stringstream 都继承自std::istream,因此您可以将它们作为参数传递,并且您的解析器无需修改即可运行。

    【讨论】:

    • 为什么是stringstream,而不是istringstream?为什么他似乎不需要额外的复杂性?
    • @James:好点子。我想我的一个坏习惯总是使用stringstream,即使ostringstreamistringstream 就足够了。
    • @James: istringstream 和 stringstream 有什么区别?
    • @ghiboz 同ifstreamfstream的区别。 stringstream 是双向的,具有所有额外的管理。 (在实践中,我从不使用双向流;这种成语不太合适,它们根据流类型有不同的语义。)
    【解决方案2】:
    #include <sstream>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    void mung( istream & is ) {
        char c;
        while( is >> c ) {
            cout << c << endl;
        }
    }
    
    int main( int argc, char *argv[] ) {
        if ( argc > 1 ) {
            ifstream ifs( argv[1] );
            mung( ifs );
        }
        else {
            istringstream iss( "here is some text to mung" );
            mung( iss );
        }
    }
    

    【讨论】:

      【解决方案3】:

      正如其他人所说,您可以使用std::istringstream,但在这种情况下, 我更喜欢已弃用(但始终存在)std::istrstream。要么 只需创建一个简单的memory_streambuf,带有imemorystream 和 一个omemorystream:如果你不需要双向,也不需要支持 求,memory_streambuf 不到 10 行代码,总是 有用,并且省去了很多其他解决方案的复杂性。 (如果你只做一次,当然,使用现有的解决方案 是首选。但我发现memory_streambuf 在 很多案例。)

      【讨论】:

      • 出于兴趣,为什么偏爱 istrstream?
      • @unaperson 简单。并且在一定程度上可能是习惯,但如果他有char[](由char* 指向),那么istrstream 可以直接使用; istringstream 需要转换为 string。没什么大不了的,如果istrstream 不可用,我会使用istringstream,但既然是,为什么不使用可以完全满足您需要的流。 (对于输出来说,差异更显着,因为ostrstream会在输出太多字符时停止并声明错误。)
      猜你喜欢
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 2012-07-01
      • 2011-07-04
      • 1970-01-01
      • 2013-12-31
      相关资源
      最近更新 更多