user2498593
user2498593

Reputation: 21

how to open a file by its full path given by user?

I have written this code. I want to ask from user the full path of a file and then go to that path and open file. But unfortunately the program cannot find the file. for excample I have created a file in this path G:\project 2\newfile but when I type this in the c++ console it says that "Error while opening the file". I really need to solve this problem. please help me with this. thanks

#include <iostream>
#include <fstream>
#include <conio.h>
#include <windows.h>

using namespace std;

int main()
{
    string address;
    cout << "Enter the full path of the file" << endl;
    cin >> address;
    ifstream file(address.c_str());

    if (!file) {
        cout << "Error while opening the file" << endl;
        return 1;
    }

    return 0;
}

Upvotes: 2

Views: 3072

Answers (1)

Cory Klein
Cory Klein

Reputation: 55690

Your application is failing because you aren't properly handling spaces in the filename.

Try this instead of cin >> address;:

getline(cin,address);

See this question for the difference between cin and getline.

Upvotes: 5

Related Questions