2

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;
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
user2498593
  • 21
  • 1
  • 2

1 Answers1

5

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.

Community
  • 1
  • 1
Cory Klein
  • 51,188
  • 43
  • 183
  • 243