我习惯于编写带有文件名或读取的小命令行工具std::cin,所以我一直在使用这种模式:
int main(int argc, char* argv[])
{
std::string filename;
// args processing ...
std::ifstream ifs;
if(!filename.empty())
ifs.open(filename);
std::istream& is = ifs.is_open() ? ifs : std::cin;
std::string line;
while(std::getline(is, line))
{
// process line...
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在阅读Stack Overflow上的一个问题之后,我尝试修改我常用的模式,以满足从文件或文件中读取的需要std::istringstream.令我惊讶的是它不会编译并给出这个错误:
Run Code Online (Sandbox Code Playgroud)temp.cpp:164:47: error: invalid initialization of non-const reference of type ‘std::istream& {aka std::basic_istream<char>&}’ from an rvalue of type ‘void*’ std::istream& is = ifs.is_open() ? ifs : iss; // won't compile
在我看来,它试图将std::istringstreamobject(iss)转换为布尔值并获取它operator void*(). …