为什么我不能将 cin/cout 放在一个函数中并从 main() 调用该函数

Why I can not put cin/cout in a function and call that function from main()

本文关键字:函数 一个 调用 main 不能 cin cout 为什么      更新时间:2023-10-16

我想将 in/output 封装到一个函数中并从 main 调用该函数,但编译器在我这样做后向我显示奇怪的错误

ifstream open_file(){
    ifstream in;
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());
    while(true){
        if (in.fail()){
            cout << "Plean Enter File Name Again: ";
            cin >> filename;
            in.clear();
            in.open(filename.c_str());
        }
        else
            break;
    }
    return in;
}

从主调用它

int main(){
    ifstream in;
    in = open_file();
    return 0;
}
错误

(7 错误)

Description Resource    Path    Location    Type
‘std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem

编译器错误并不奇怪,因为它是正确的,因为无法复制流。函数 open_file不支持的值返回ifstream对象。

ifstream open_file()
{
    ifstream in;
    // snip
    return in; // return the stream by value requires a copy.
}

一种选择是对流的引用作为参数传递给open_file函数。这将允许 open_file 函数处理打开文件,并且任何调用它的函数都能够读取/写入文件。以下代码应该会让您回到正轨...

bool open_file(ifstream& in)
{
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());
    // [snipped code].
    return in.is_open();
}
int main()
{
    ifstream in;
    if(open_file(in))
    {
        // do something if the file is opened
    }
    return 0;
}
std::ifstream不可

复制,但在C++11中,它是可移动的,所以如果你在启用C ++ 11的情况下编译(-std=c++11用于gcc/clang),你的代码应该编译。

相关文章: