【问题标题】:ifstream, Getline returns a memory addressifstream, Getline 返回一个内存地址
【发布时间】:2015-08-21 17:57:58
【问题描述】:

我有以下代码:

std::ifstream report( fileToRead );
cout << "leyendo archivo: " << fileToRead << endl;
std::string line;
cout << std::getline(report,line) << endl;
report.close();

但是 cout 给出以下结果:0x28fe64 我能做什么?

【问题讨论】:

    标签: c++ string file pointers


    【解决方案1】:

    基于此参考,http://www.cplusplus.com/reference/string/string/getline/

    getline 函数返回对ifstream 对象的引用,这就是打印地址的原因。

    您需要cout &lt;&lt; line; 才能打印出阅读的内容。

    我也没有重复您的错误,您使用的是哪个版本的 g++ 和操作系统?我的 g++ 如下:

    配置: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM 版本 6.1.0 (clang-602.0.53) (基于 LLVM 3.6.0svn) 目标: x86_64-apple-darwin14.3.0 线程模型:posix

    #include <fstream>
    #include <iostream>
    using namespace std;
    
    int main(int argc, char * argv[]){
        char * fileToRead= "a.txt";
        std::ifstream report( fileToRead );
        cout << report << endl;
    
        cout << "leyendo archivo: " << fileToRead << endl;
        std::string line;
        cout << std::getline(report,line) << endl;
        cout << std::getline(report,line) << endl;
        cout << std::getline(report,line) << endl;
        cout << std::getline(report,line) << endl;
        cout << std::getline(report,line) << endl;
        cout << std::getline(report,line) << endl;
        report.close();
    }
    

    我得到的结果是:

    1
    leyendo archivo: a.txt
    1
    1
    1
    0
    0
    0
    

    ifstream 似乎被转换为布尔变量,指示 ifstream 是否存在任何文件操作错误。最后三个零是由于没有更多行可读取。

    【讨论】:

    • 实际上,它打印地址的原因是从ifstreamvoid * 的转换,即[我相信在失败时恰好返回thisNULL]
    • 您非常有帮助,我已经修复了代码并且工作了!但我不知道 getline 不从我的文件中读取的原因,它显示了一个“代码”\n“代码”我在 stackoverflow 上基于 cmets 编写了这段代码,它应该可以工作。
    • 您关注的是哪些 cmets 或帖子?你正在阅读的文件是什么? 'code' 是输出到控制台的字符串吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多