【问题标题】:Opening a file in C++ based on "String" input from the user根据用户的“字符串”输入在 C++ 中打开文件
【发布时间】: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 &gt;&gt; ch) { cout &lt;&lt; ch; } 比你的循环更容易观察,并且在所有错误条件下都能可靠地工作,而不仅仅是eof。 (而且您不需要显式的 closefstream 会自行清理。)

标签: c++ io file-handling


【解决方案1】:

open 函数不返回任何内容,因此您不能使用类似!file_han.open(i.c_str()) 的内容。如果您想检查打开是否正确执行,请使用file_han.fail()。更多信息请见this answer

【讨论】:

    【解决方案2】:

    该错误与能够打开带有字符串的文件无关(顺便说一句,您正在这样做)。错误是 open 是一个 void 函数,您试图将其视为返回 bool

    file_han.open(i);打开文件然后用if (!file_han.is_open())测试打开是否失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多