我有一个包含“-3.5”的“QString”,但是如果我尝试使用“toInt”方法将其转换为整数,它会返回 0。为什么?
QString strTest = "-3.5";
int intTest = strTest.toInt();
qDebug() << intTest;
intTest 将为 0 ?
最佳答案
相对于std::stoi
和来自标准库的流,Qt 字符串要求整个字符串是一个有效的整数来执行转换。您可以使用 toDouble
作为解决方法。
您还应该使用可选的 ok
参数来检查错误:
QString strTest = "-3.5";
book ok;
int intTest = strTest.toInt(&ok);
if(ok) {
qDebug() << intTest;
} else {
qDebug() << "failed to read the string";
}
关于c++ - Qt QString toInt() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817068/