ifstream dont accept a string as input.

(Im sorry if u saw any english erros becouse english is not my main language)

Hey Guys, I recently made a function to read a file, but she has a problem that i cant solve. The error appears on "ifstream".
Can anyone helpme solve that problem, thak you.

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>
using namespace std;

void readFile(string input)
{

    string finalString, txt = ".txt" , mark = "\"", writer;
    finalString = mark + input + txt + mark;
    ifstream filename(finalString); // error apperas here
    if(filename.is_open())
    {
        while(getline(filename,writer))
        {
            cout << writer << endl;
        }
        filename.close();
    }
    else
    {
        cout << "Fail opening  " << finalString << endl;
    }
}


int main()
{
    string file;
    cin >> file;
    readFile(file);
}
Last edited on
#include <string>
But it keeps giving me error.
What is the text of the error message?
error : no matching function for call to "std::basic_ifstream<char>::basic_ifstream...
Enable C++11 support with -std=c++11

Or modify line 10 to:
1
2
// ifstream filename(finalString);
ifstream filename( finalString.c_str() );
It worked thank you!
Now it appears another problem, I rewrited the code I but cant open a file that I created.

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
33
34
35
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void readFile(string input)
{

    string finalString, txt = ".txt" , mark = "\"", writer;
    finalString = mark + input + txt + mark;
    ifstream filename;
    filename.open(finalString.c_str() );
    if(filename.is_open())
    {
        while(getline(filename,writer))
        {
            cout << writer << endl;
        }
        filename.close();
    }
    else
    {
        cout << "ERROR : CANNOT OPEN " << finalString;
    }
}



int main()
{
    string file;
    cin >> file;
    readFile(file);
}
Last edited on
Hello troyaan,

Try this: finalString = input + txt;. You do not need to put the string in ("")s.

Andy

Edit: typo
Last edited on
It worked thank you :D
Topic archived. No new replies allowed.