Manually enter ifstream file name

Can I manually enter the file name inside the terminal?

For example, a program will ask me which file I want to open. I will manually enter "test.txt" and it will open test.txt. However, my compiler produces the following error:

no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'

My code is:

int main() {
    string input;
    cout << "Please enter the name of the file\n";
    cout << "Input: ";
    getline (cin, input);

    ifstream file (input);

    if (file.is_open()) {
        // blah
    } else {
        // blah
    }
}

How can I manually enter the name of a text file?

+4
source share
1 answer

If you are using an older (pre-C ++ 11) compiler, you will have to use:

ifstream file (input.c_str());

, ++ 98 std::string, ( ), ++ 98 - , , char const * (.. C), std::string.

, , char const * std::string, ( ) - , , - .

+1

All Articles