I want to ask user the full path where the file exists and then keep the path in an array. So during the program I want to open the file that is exists in that place. but unfortunately I don't know how to open the file. I tried the following code but it's not true.
string address;
cin>>address;
ifstream file(address);
How do I open the file this way?
Actually that code works as it is – at least in the current version, C++11.
Before that, you need to convert the string to a C-style string:
ifstream file(address.c_str());
Although you should beware of spaces in the file’s path as CapelliC mentioned in his (now-deleted) answer; in order to ensure that the user can enter paths with spaces (such as “~/some file.txt”), use std::getline instead of the stream operator:
getline(cin, address);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With