I was trying to write a program that takes an input from a file which is located in Desktop not the default directory where the program is saved

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main()
{
    ifstream fin;
    string str="C:\Documents and Settings\shankhs\Desktop\ccs\Assignment CCS.txt",temp="";
    cout<<str<<endl;
    for(int i=0;i<str.size();i++)
    {
            if(str[i]=='\\')
                            temp+="\\";
            temp+=str[i];
            cout<<str[i]<<endl;
            }
            cout<<temp<<" "<<str<<endl;
    fin.open((char *)&str,ios::in);
    if(!fin)
            cout<<"Cant";
    else
        cout<<"can";
        
    system("pause");
    return 0;
}

The escape character '\' is causing a lot of trouble as '\' is not taken by the variable since its a special character (I have taken input in str but actually I have to take it from user who will just copy and paste the path and filename) how to get out of this mess????
PLZ HELP!

>fin.open((char *)&str,ios::in);
Eew, use c_str instead:

fin.open ( str.c_str(), ios::in );

You only have to escape a backslash in literals, so the following will work fine:

string str="C:\\Documents and Settings\\shankhs\\Desktop\\ccs\\Assignment CCS.txt"

For input, you don't need to worry about escaping a backslash because it's already correct.

By the way, in your code you go to the effort of sanitizing str using temp, then you try to open str instead of temp... :icon_rolleyes:

I was a bit confused thanx for your quick reply
Final code

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
    ifstream fin;
    string temp="";
    string str;
    getline(cin,str);
    cout<<str<<endl;
    for(int i=0;i<str.size();i++)
    {
            if(str[i]=='\\')
                            temp+="\\";
            temp+=str[i];
            //cout<<str[i]<<endl;
            }
            
            str=temp;//cout<<temp<<" "<<str<<endl;
    fin.open(str.c_str(),ios::in);
    if(!fin)
            cout<<"Cant";
    else
        cout<<"can";
        
    system("pause");
    return 0;
}

Problem solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.