在 qt 中比较字符串不起作用
Comparing strings in qt doesn't work
我正在尝试比较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"}));
}
您的问题出在其他地方,或者您的调试器在骗您。
相关文章:
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- boost::spirit::x3 中的简单字符串解析器不起作用
- 用于拆分空格字符串的程序不起作用
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 从中间器转换字符串不起作用,出了什么问题?
- C++字符串不起作用
- 如何获取链表中的所有"next"节点?构建调用字符串不起作用
- 布尔表达的字符串不起作用
- Rapidjson 输出到字符串不起作用
- 为什么写入我的字符串不起作用
- 在 qt 中比较字符串不起作用
- 对于字符串不起作用的循环
- 通过引用字符 2 维调用字符串不起作用
- C++ cout 字符串不起作用.请指教
- C++if语句比较字符串不起作用
- glutBitmapString/glutStrokeString似乎需要常量无符号字符* - 字符串不起作用
- Arduino 子字符串不起作用