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开发者_如何学JAVA path ;
path = "C:\MyLife\Image Collection" ;
for( int i=0 ; i < path.size() ; i++ )
{
if( path[i] == "\" )
path[i] = "/" ;
}
qDebug() << path ;
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)
You need to escape \
if( path[i] == '\\' )
Same with
path = "C:\\MyLife\\Image Collection" ;
http://en.wikipedia.org/wiki/C_syntax#Backslash_escapes
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 \\
.
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!)
- Strings cannot be compared directly in C/C++.
- Characters can be compared.
- "\" is string, whereas '\' is a character.
What does work for me for Qt4 on Linux is using:
std::replace( path.begin(), path.end(), QChar('\\'), QChar('/') );
None of the Qt functions work, obviously.
精彩评论