Abdul Mughni Ahmad
Abdul Mughni Ahmad

Reputation: 1

Opening a file in C++ based on "String" input from the user

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(); 
    }
}

Upvotes: 0

Views: 82

Answers (2)

Salvankar
Salvankar

Reputation: 101

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.

Upvotes: 1

jkb
jkb

Reputation: 2450

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

Upvotes: 1

Related Questions