如何将QString转换为int?

use*_*614 54 c++ string int qstring qt

我有一个QString在我的消息来源.所以我需要将它转换为没有"Kb"的整数.

我试过Abcd.toInt()但它不起作用.

QString Abcd = "123.5 Kb"
Run Code Online (Sandbox Code Playgroud)

Nee*_*asu 83

您的字符串中没有所有数字字符.所以你必须按空间划分

QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt();    //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat();  //convert the first part to float
Run Code Online (Sandbox Code Playgroud)

更新:我正在更新旧答案.这是对具体问题的直接回答,并有严格的假设.但正如@DomTomCat在评论和@Mikhail的回答中所指出的那样,一般应该检查操作是否成功.因此,使用布尔标志是必要的.

bool flag;
double v = Abcd.split(" ")[0].toDouble(&flag); 
if(flag){
  // use v
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您将该字符串作为用户输入,那么您还应该怀疑该字符串是否真的可以与空格分开.如果假设可能破坏,则更优选正则表达式验证器.像下面这样的正则表达式将提取浮点值和'b'的前缀字符.然后,您可以安全地将捕获的字符串转换为double.

([0-9]*\.?[0-9]+)\s+(\w[bB])
Run Code Online (Sandbox Code Playgroud)

您可以使用如下所示的实用程序功能

QPair<double, QString> split_size_str(const QString& str){
    QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
    int pos = regex.indexIn(str);
    QStringList captures = regex.capturedTexts();
    if(captures.count() > 1){
        double value = captures[1].toDouble(); // should succeed as regex matched
        QString unit = captures[2]; // should succeed as regex matched
        return qMakePair(value, unit);
    }
    return qMakePair(0.0f, QString());
}
Run Code Online (Sandbox Code Playgroud)


con*_*oly 8

您在此处的字符串包含带有单位的浮点数.我建议将该字符串拆分为数字和单位部分QString::split().

然后使用toDouble()获取浮点数并根据需要进行舍入.


Mik*_*ail 8

不要忘记检查转换是否成功!

bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用:

QString str = "10";
int n = str.toInt();
Run Code Online (Sandbox Code Playgroud)

输出:

n = 10
Run Code Online (Sandbox Code Playgroud)

  • 与大多数答案所提出的一样,对我来说,这是一个多余的回应。 (2认同)

Sam*_*ves 5

用于.toInt()int.toFloat()用于 float 和.toDouble()用于 double

toInt();