Appended file path not working

I need to append file path for some particular program. But the problem is when I append it like below, it gets error whether filepath seems to be C:/Users/My/Desktop/C++/1.txt
1
2
3
4
5
6
7
8
int i=1;
    stringstream str;
    str<<"C:/Users/My/Desktop/C++/"<<i<<".txt";
    string filepath=str.str();
    cout<<filepath;
    ifstream ipf(filepath);
    if(ipf)
{ do some thing...}


But if it was like this no error, program work as desired.
1
2
3
4
5
6
7
8
int i=1;
    stringstream str;
    str<<"C:/Users/My/Desktop/C++/"<<i<<".txt";
    string filepath=str.str();
    cout<<filepath;
    ifstream ipf("C:/Users/My/Desktop/C++/1.txt");
    if(ipf)
{ do some thing...}

Any help will be appreciated...
Before C++11 there were no ifstream constructor accepting std::string, only const char* so you had to do:
 
ifstream ipf(filepath.c_str());
c++ forces you to put two backslashes instead of one and a backslash in the beginning and at the end. Try this:

1
2
3
4
5
6
7
8
9
    
    int i=1;
    stringstream str;
    str<<"/C://Users//My/Desktop//C++//"<<i<<".txt/";
    string filepath=str.str();
    cout<<filepath;
    ifstream ipf("/C://Users/My//Desktop//C++//1.txt/");
    if(ipf)
{ do something...}
But he's not using backslashes. / is a forward slash.
same diff
same diff
Not really, they are two completely different characters. \ is a backslash (escape sequence) and / is a forward slash. It's almost like saying r and c are the same letter.
whatever... lets just help with this persons program.
Thank you for all replies.. my problem has been solved.
I have already tried using double back-slashes & forward back slashes. But problem was not solved.

Peter87 suggestion solve my problem.

ifstream ipf(filepath.c_str());
Last edited on
Topic archived. No new replies allowed.