Hi all, I am trying to write a little function to convert a file path into one that can be used by ifstream.
I need the string file to be in the form of: C:\\users\\administrator\\desktop\\file.txt
But I want the user to enter through cmd: C:\users\administrator\desktop\file.txt
I have the following already:
1 2 3
for (int i = 0; i < 20; i++) {
file.replace(file.find("\\"), 1, "\\\\");
}
This works however when it loops it just finds the first \ so the output is c:\\\\\\\\\\users....etc. Is there anyway of finding the first \, changing it to \\, then finding the second etc until the end of the string?
if the file.replace was only run once, only the first \ would be replaced, the idea of the for loop was to run it again such that every \ was replaced, however what it actually does is replace the first \ 20 times! 20 was just a random number, I assumed that the user wouldnt be putting in a path with more than 20 \ in.
The first argument of your replace function 'file.find("\\")' will search for the first occurrence of '\\'. The length of this should be '1'. This will be replaced by '\\\\'.
Now imagine we have your string file:
C:\\users\\administrator\\desktop\\file.txt
Searching for the first occurence of '\\' and replacing it with '\\\'
C:\\\\users\\administrator\\desktop\\file.txt (length to be replaced is '1', not '2' ?)
Try:
file.replace(file.find("\\"), 2, "\");
(haven't tested this, please post if it does or doesnt work)
I was under the impression that "\\" equates to '\' in the string (hence the 1 not 2) and "\\\\" equates to \\ in the string, as with when using cout? This seems to be how it functioned in my first example.
Running file.replace(file.find("\\"), 1, "\\\\"); just the once replaces the first \ with \\ as expected. How do you get it to replace the second, third, fourth, etc \ with \\ ? This is why I tried the for loop!
Note also: tested file.replace(file.find("\\"), 2, "\"); and it does not compile
This is just to show how it can be done. The second parameter of find() is an offset where to start the search (default 0) you have to use the last found offset plus the chars to skip. std::string::npos tells whether anything was found.
But you really don't need it. Pass the string entered by the user to the ifstream and you're done!
Thank you! What you have written makes sense, but what makes more sense is that I dont actually need to swap it at all, I dont know what I didnt test this before : | Thanks for your help, much appreciated!