【发布时间】:2021-09-06 16:23:29
【问题描述】:
我正在尝试根据字符串用户输入打开一个文件。但它正在显示
[Error] could not convert 'file_han.std::basic_fstream<_CharT, _Traits>::open<char, std::char_traits<char> >(i.std::basic_string<_CharT, _Traits, _Alloc>::c_str<char, std::char_traits<char>, std::allocator<char> >(), std::operator|((std::_Ios_Openmode)8u, (std::_Ios_Openmode)16u))' from 'void' to 'bool'.
我搜索了互联网,我只能找到基于用户输入的单字母字符打开的文件。没有基于字符串输入打开文件的代码。 这是我的代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream file_han;
int a;
char f;
string i;
cout<<"Enter the name of the file: \n";
cin>>i;
if (!file_han.open(i.c_str()))
{
cout << "File not created!";
}
else
{
file_han<<"1";
file_han<<"2";
char ch;
while (1)
{
file_han >> ch;
if (file_han.eof())
break;
cout << ch;
}
file_han.close();
}
}
【问题讨论】:
-
您的教科书、课堂笔记或教程对
open函数以及它(可能)返回的内容有何看法?它是如何在您阅读的书籍、教程和其他示例中使用的? -
在不相关的注释中,
open函数可以接受std::string参数。所以不需要i.c_str(),简单的i就足够了。 -
另外,
while (file_han >> ch) { cout << ch; }比你的循环更容易观察,并且在所有错误条件下都能可靠地工作,而不仅仅是eof。 (而且您不需要显式的close。fstream会自行清理。)
标签: c++ io file-handling