Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

path - How to put two backslash in C++

i need to create a function that will accept a directory path. But in order for the compiler to read backslash in i need to create a function that will make a one backslash into 2 backslash.. so far this are my codes:

string stripPath(string path)
{       
        char newpath[99999];
        //char *pathlong;
        char temp;
        strcpy_s(newpath, path.c_str());
        //pathlong = newpath;
        int arrlength = sizeof(newpath);

            for (int i = 0; i <= arrlength ;i++)
            {
                if(newpath[i] == '\')
                {
                    newpath[i] +=  '\';
                    i++;
                }
            }
            path = newpath;
        return path;
} 

this code receives an input from a user which is a directory path with single backslash. the problem is it gives a dirty text output;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

int arrlength = sizeof(newpath); causes the size of your entire array (in chars) to be assigned to arrlength. This means you are iterating over 99999 characters in the array, even if the path is shorter (which it probably is).

Your loop condition also allows goes one past the bounds of the array (since the last (99999th) element is actually at index 99998, not 99999 -- arrays are zero-based):

for (int i = 0; newpath[i]] != ''; i++)

Also, there is no reason to copy the string into a character array first, when you can loop over the string object directly.

In any case, there is no need to escape backslashes from user input. The backslash is a single character like any other; it is only special when embedded in string literals in your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...