【问题标题】:Why I can not put cin/cout in a function and call that function from main()为什么我不能将 cin/cout 放在一个函数中并从 main() 调用该函数
【发布时间】:2015-01-01 00:23:50
【问题描述】:

我想将输入/输出封装到一个函数中并从 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;
}

从 main 调用它

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

【问题讨论】:

标签: c++


【解决方案1】:

编译器错误并不奇怪,因为流无法复制,所以它很明显。函数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;
}

【讨论】:

    【解决方案2】:

    std::ifstream 不可复制,但对于 C++11,它是可移动的,因此如果您在启用 c++11 的情况下进行编译(-std=c++11 用于 gcc/clang),您的代码应该可以编译。

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多