0

I am trying to open a file based on the String user input. But it is showing

[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'.

I have searched the internet, all I can find is opening file based on single letter char input from the user. No code for Opening file based on String Input. Here is my code:

#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(); 
    }
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    What does your text books, class notes or tutorials say about the [`open`](https://en.cppreference.com/w/cpp/io/basic_fstream/open) function and what it (possibly) returns? How is it used in your books, tutorials and other examples you've read? – Some programmer dude Jun 23 '21 at 06:06
  • 1
    On an unrelated note, the `open` function can accept a `std::string` argument. So no need for `i.c_str()`, plain `i` is enough. – Some programmer dude Jun 23 '21 at 06:06
  • Also, `while (file_han >> ch) { cout << ch; }` is easier on the eye than your loop, and works reliably with all error conditions, not just `eof`. (And you don't need the explicit `close`. An `fstream` cleans up after itself.) – molbdnilo Jun 23 '21 at 07:03

2 Answers2

1

The error has nothing to do with being able to open a file with a string (which you are doing, by the way). The error is that open is a void function which you are attempting to treat as returning bool.

Open the file with file_han.open(i); Then test whether the open failed with if (!file_han.is_open()).

jkb
  • 2,376
  • 1
  • 9
  • 12
1

The open function does not return anything, and hence you cannot use something like !file_han.open(i.c_str()). If you would like to check if the open gets executed correctly, use file_han.fail(). More about it is in this answer.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Salvankar
  • 91
  • 6