【发布时间】: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 我能做什么?
【问题讨论】:
我有以下代码:
std::ifstream report( fileToRead );
cout << "leyendo archivo: " << fileToRead << endl;
std::string line;
cout << std::getline(report,line) << endl;
report.close();
但是 cout 给出以下结果:0x28fe64 我能做什么?
【问题讨论】:
基于此参考,http://www.cplusplus.com/reference/string/string/getline/。
getline 函数返回对ifstream 对象的引用,这就是打印地址的原因。
您需要cout << 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 是否存在任何文件操作错误。最后三个零是由于没有更多行可读取。
【讨论】:
ifstream 到void * 的转换,即[我相信在失败时恰好返回this 或NULL]