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(); 
    }
}
3
  • 1
    What does your text books, class notes or tutorials say about the open function and what it (possibly) returns? How is it used in your books, tutorials and other examples you've read? Commented Jun 23, 2021 at 6: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. Commented Jun 23, 2021 at 6: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.) Commented Jun 23, 2021 at 7:03

2 Answers 2

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()).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.