如何显示我在第一个函数中已经创建的文件的内容
How can I display the content of the file that I already created in the first function?
//it is a function to take file name and create it.
void createfile(string filename)
{
ofstream file;
file.open(filename,ios::out);
if(file.fail())
{
cout<<"file is failed"<<endl;
}
else
{
cout<<"file is opened"<<endl;
}
}
//it is a function which takes name of file and display it's content.
void displaycontent(string name)
{
ifstream file;
file.open(name);
string y;
while(!file.eof())
{
getline(file,y);
cout<<y<<endl;
}
}
如何显示我在第一个函数中已经创建的文件的内容?
int main()
{
string filename;
cin>>filename;
createfile(filename);
displaycontent(filename);
return 0;
}
该程序永远不会将任何内容写入文件,因此没有内容可以显示。另外,循环是错误的。如果发生错误读取文件,则file.eof((永远不会是正确的,以下将永远循环。
void displaycontent(string name)
{
ifstream file;
file.open(name);
string y;
while(!file.eof()) // WRONG
{
getline(file,y);
cout<<y<<endl;
}
}
相反,您想要此(省略错误处理(:
void display_file(const string &file_name) // Note pass by reference
{
std::ifstream file;
file.open(file_name);
std::string y;
while(std::getline(file,y)) {
std::cout << y << 'n';
}
}
或更好,
void display_file(const string &file_name)
{
std::ifstream file(file_name);
std::cout << file.rdbuf();
}
在显示功能(在其他范围内(中调用创建功能...随着创建函数按值传递,因此内部内部发生的任何更改都将留在范围内
相关文章:
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何创建一个对象创建函数,该函数将由与其关联的名称调用?
- 创建函数变体向量时"No matching function for call"错误
- C++ 在映射中创建函数指针向量
- 以编程方式在 C++ 中创建函数
- 如何创建函数可能使用自定义可比C++?
- 编译错误,未创建函数/方法! 对于 brms 模型
- Cython 创建 C 函数别名
- 创建函数指针数组
- 动态创建函数并获取指针
- 混合模板类型的模板参数包(std::使用可选参数重新创建函数)
- 如何创建函数原型命名空间
- 无法创建函数数组
- 在为STD模板函数创建函数对象时,还要还原样板
- 是否可以在C++中声明基类,以便只能通过创建函数创建从它派生的类
- 将原始指针移动到已创建函数中的下一个字符
- qjsonObject如何创建函数
- 尝试在别人的代码中C++创建函数(A* 搜索)
- 在C++中通过模板包重新创建函数签名和调用
- 创建函数时接收"expected unqualified-id"