Changing the backslash for a slash in a QString

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

QString path ; path = "C:\MyLife\Image Collection" ; for( int i=0 ; i < path.size() ; i++ ) { if( path[i] == "\" ) path[i] = "/" ; } qDebug() << path ; 
+4
source share
6 answers

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

ooh, and QDir has a nice static method for you that does exactly what you want:

  path = QDir::fromNativeSeparators(path); 

There is no excuse to do this manually (with errors)

+13
source

You need to go out \

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

Same thing with

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

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

+5
source

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

+3
source
  • Strings cannot be compared directly in C / C ++.
  • Symbols can be compared.
  • "\" is a string, while the \\ character is a character.
+2
source

No one has fixed both of your errors in the same message, so here goes:

  if( path[i] == '\\' ) // Double backslash required, and path[i] = '/' ; // single quote (both times!) 
+1
source

What works for me for Qt4 on Linux is:

 std::replace( path.begin(), path.end(), QChar('\\'), QChar('/') ); 

None of the Qt functions work, obviously.

0
source

Source: https://habr.com/ru/post/1345318/


All Articles