string variable needs to be const char

I am writing a simple program that asks the user to enter a file name then the program counts the number of files. I have gotten the body of the program to work when I hard code the file name into the code. However, when I try to use the input form the users as the file name go to. I get a complier error. I believe this is because the function wants the file name in a const char format and not a string format. Please any ideas on how to get this to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <fstream>
#include <vector>
#include <windows.h>

using namespace std;

int main()
{
    string filename;
    cout << "Enter filename\n";
    cin>>filename;
  
    ifstream file_reader(filename);

    if(file_reader.is_open() == false)
    {
        cout<<"file not found\n";
        exit(0);
    }

    vector<string>counts;
    while(file_reader.eof() != true)
    {
        string counter;
        file_reader>>counter;
        counts.push_back(counter);
    }
    cout<<"Found "<<counts.size()<<" words.\n";
    return 0;
}
Two options:

The preffered option is to use a c++11 compliant compiler, and specify to compile in c++11 mode. For example, using GCC or Clang you would specify -std=c++11 in the command line. IDE's probably have a build setting to let you do this. This is to provide the overloading for std::filebuf::filebuf() that allows to construct a file from a std::string.

The other option is to use std::string::c_str() to get the underlying char array, like so:
 
ifstream file_reader(filename.c_str());
Topic archived. No new replies allowed.