基于条件的iStream引用

Istream reference based on condition

本文关键字:iStream 引用 条件 于条件      更新时间:2023-10-16

我应该如何在C 中做这样的事情?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string input_filename_ = "";
istream& input = (input_filename_ == "") ? cin : ifstream(input_filename_, ifstream::in);

我遇到了这个错误,不知道为什么。

e0330" std :: basic _istream&lt; _ elem,_traits> :: basic _istream(std :: basic_istream&lt; _traits> :: ___________________ _ myt(在" D: Program Files Visual Studio 2017 VC Tools MSVC MSVC 14.11.25503 Inclupper istream"的第55行中声明。

您无法将临时性绑定到 non-const 参考。您必须创建一个真实的变量并绑定:

ifstream ifs(input_filename, ifstream::in); // a real variable
istream& input = input_filename.empty() ? cin : ifs; // that should bind properly

通常,我做的事情与此相似,以确保用户提供了一个文件名并正确打开文件:

std::ifstream ifs;
if(!file_name.empty()) // do we have a file name?
    ifs.open(file_name); // try to open it
if(!ifs) // if we tried to open it but it failed
    throw std::runtime_error(std::string(std::strerror(errno)) + ": " + file_name);
// only attach file to reference if user gave a file name
std::istream& in = file_name.empty() ? std::cin : ifs;

当您使用

istream& input = (input_filename_ == "") ? cin : ifstream(input_filename_, ifstream::in);

表达的最后一部分是暂时的。您不能使用它来初始化非const参考。

您必须对其进行稍有不同的处理。

std::ifstream str;
std::istream* str_ptr = &std::cin;
if (input_filename_ != "")
{
   str.open(input_filename_);
   str_ptr = &str;
}
std::istream& input = *str_ptr;