为什么我不能将 cin/cout 放在一个函数中并从 main() 调用该函数
Why I can not put cin/cout in a function and call that function from main()
我想将 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),你的代码应该编译。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何仅为一个函数添加延迟
- 构造函数正在调用一个使用当前类类型的函数
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- C :基类调用自己的虚拟函数 - 一个反图案
- 如何在这个交换函数(一个单独的链表)中找到错误
- 两个相同的函数(一个使用模板模式,另一个不使用)
- 你怎么能一次给一个函数一个参数呢
- 为什么要做两个函数?(一个是非const,另一个是const)
- 当代码在其他地方使用时,如何保证函数一个接一个地被调用