I have a problem opening files in C++ that has spaces in its name. For instance, to open the file read me.txt
.
This is the code I have so far involving one command that reads a file and outputs the word count to the console:
string choice, word, fname;
ifstream input;
int l, count = 0;
if(choice == "wc" || choice == "WC" || choice == "Wc")
{
getline(cin, fname);
input.open(fname.c_str());
cout << fname << endl;
if(input.fail())
{
cerr << " Error: failed to open the file: " << fname << endl;
input.clear();
}
else
{
w = 0;
while (input >> word)
w++;
input.close();
count = w;
cout << fname << " has a Word Count of: " << count << " words \n" << endl;
}
}
I know that the stream function c_str()
cannot read more than one string after a space. I was thinking of using substring but I'm not entirely sure how to proceed. Could you guys help me out?
did you try this(http://www.cplusplus.com/forum/beginner/39687):
In a literal string the \
character is interpreted as an escape code to allow you to embed characters that otherwise cannot be entered or are non-printable. For example to embed a newline in a literal string you cannot just hit the Enter key while typing the literal string because the editor would respond by actually starting a new line. So instead you type "\n
", i.e., "This is on the first line \n This is on the second line
". To enter a '\
' character you need to escape it by entering two slashes. The first slash is the escape character and the second slash is the slash character being embedded.
example: C:\\Program Files\\filename.txt
EDIT:
The user does not enter the escape characters just the file name. The program then has to deal with the spaces and the path backward slash. \n
designates new line but it is made up of an escape character followed by the n character.