在 qt 中比较字符串不起作用

Comparing strings in qt doesn't work

本文关键字:字符串 不起作用 比较 qt      更新时间:2023-10-16

我正在尝试比较Qt中默认值的两个字符串,但它总是失败。 它总是假的

如果 group == default,则语句转到 s.beginGroup,但是该组称为 Default。我不知道问题出在哪里,这太奇怪了。

 foreach (const QString &group, s.childGroups()) {
        if(group =="Default")
            continue;
        s.beginGroup(group);
        Profile *profile = new Profile();
        profile->setObjectName(group);
        profile->load(s);
        s.endGroup();
        m_Profiles << profile;
    }

如果您的编译器启用了 C++11,则最好切换到 ranged-for:

for (const QString& group : s.childGroups())
{ ... }

范围循环按预期支持continue关键字

此外,必须将CONFIG += c++11添加到项目的 *.pro 文件中

Qt中foreach的定义解析为以下内容:

#  define Q_FOREACH(variable, container)                                
for (QForeachContainer<QT_FOREACH_DECLTYPE(container)>  _container_((container)); 
 _container_.control && _container_.i != _container_.e;         
 ++_container_.i, _container_.control ^= 1)                     
    for (variable = *_container_.i; _container_.control; _container_.control = 0)

因此,如您所见,有两个for循环,可能 continue 关键字不会继续您想要的那个,而是内部的。

在@chi的评论后编辑

Qt头文件中有一个很好的解释:

// Explanation of the control word:
//  - it's initialized to 1
//  - that means both the inner and outer loops start
//  - if there were no breaks, at the end of the inner loop, it's set to 0, which
//    causes it to exit (the inner loop is run exactly once)
//  - at the end of the outer loop, it's inverted, so it becomes 1 again, allowing
//    the outer loop to continue executing
//  - if there was a break inside the inner loop, it will exit with control still
//    set to 1; in that case, the outer loop will invert it to 0 and will exit too

如您所见,没有提到continue只有休息时间。而且在foreach文档页面上也没有提到continue:http://doc.qt.io/qt-4.8/containers.html#the-foreach-keyword 只显示中断。

对我有用:

#include <QtCore>
int main() {
   auto const kDefault = QStringLiteral("Default");
   QStringList groups{"a", kDefault, "b"};
   QStringList output;
   // C++11
   for (auto group : groups) {
      if(group == kDefault)
         continue;
      Q_ASSERT(group != kDefault);
      output << group;
   }
   // C++98
   foreach (const QString &group, groups) {
      if(group == kDefault)
         continue;
      Q_ASSERT(group != kDefault);
      output << group;
   }
   Q_ASSERT(output == (QStringList{"a", "b", "a", "b"}));
}

您的问题出在其他地方,或者您的调试器在骗您。