Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing backslash to forward slash in a QString

Tags:

c++

I have a program that gives a QString and changes every "\" to "/". It seems very simple but when I use the below code, 5 errors happen:

QString path ;
path = "C:\MyLife\Image Collection" ;
for( int i=0 ; i < path.size() ; i++ )
{
    if( path[i] == "\" )
        path[i] = "/" ;
}
qDebug() << path ;
like image 929
amiref Avatar asked Mar 26 '11 09:03

amiref


People also ask

How do you change backslash to forward slash?

Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

How do I change backslash to slash in Python?

The correct way would be s. replace('/', '\\') .

How do you do a forward slash between words?

When a slash signifies alternatives between only two words, don't use spaces before or after. When using slashes to signify alternatives between phrases or multi-word terms or compounds, a space before and after the slash makes text easier to read.

How do you use a forward slash?

We can use a forward slash to indicate that two (or more) things have a close relationship or are in opposition to each other. For example, Those two had a love/hate relationship.


4 Answers

Please, Stop the bleeding, now ! And use a cross-platform directory/path wrapper class. Qt have some : QDir, QFileInfo, QFile. Just use them.

ooh, and QDir have a nice static method for you, which does exactly what you want :

 path = QDir::fromNativeSeparators(path);

No excuse to do it manually (with bugs)

like image 184
BatchyX Avatar answered Nov 08 '22 11:11

BatchyX


You need to escape \

if( path[i] == '\\' )

Same with

path = "C:\\MyLife\\Image Collection" ;

http://en.wikipedia.org/wiki/C_syntax#Backslash_escapes

like image 36
unexpectedvalue Avatar answered Nov 08 '22 10:11

unexpectedvalue


Because the backslash \ is used as an escape character (for things like \n newline, \r carriage return, and \b backspace), you need to escape the backslash with another backslash to give you a literal backslash. That is, wherever you want a \, you put \\.

like image 3
The Communist Duck Avatar answered Nov 08 '22 10:11

The Communist Duck


Nobody has fixed both your errors in the same post, so here goes:

    if( path[i] == '\\' ) // Double backslash required, and
        path[i] = '/' ;   // single quote (both times!)
like image 2
TonyK Avatar answered Nov 08 '22 10:11

TonyK