C++ 如何将 QString 转换为 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16633555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:30:41  来源:igfitidea点击:

How to convert QString to int?

c++stringqtintqstring

提问by user2398614

I have a QStringin my sources. So I need to convert it to integer without "Kb".

我的资源中有一个QString。所以我需要将它转换为没有“Kb”的整数

I tried Abcd.toInt()but it does not work.

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

QString Abcd = "123.5 Kb"

回答by Neel Basu

You don't have all digit characters in your string. So you have to split by space

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

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

Update: I am updating an old answer. That was a straight forward answer to the specific question, with a strict assumption. However as noted by @DomTomCat in comments and @Mikhail in answer, In general one should always check whether the operation is successful or not. So using a boolean flag is necessary.

更新:我正在更新一个旧答案。这是对特定问题的直接回答,并带有严格的假设。然而,正如@DomTomCat 在评论中和@Mikhail 在回答中所指出的那样,通常应该始终检查操作是否成功。所以使用布尔标志是必要的。

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

Also if you are taking that string as user input, then you should also be doubtful about whether the string is really splitable with space. If there is a possibility that the assumption may break then a regex verifier is more preferable. A regex like the following will extract the floating point value and the prefix character of 'b'. Then you can safely convert the captured strings to double.

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

([0-9]*\.?[0-9]+)\s+(\w[bB])

You can have an utility function like the following

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

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());
}

回答by Mikhail

Don't forget to check if the conversion was successful!

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

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

回答by confusopoly

The string you have here contains a floating point number with a unit. I'd recommend splitting that string into a number and unit part with QString::split().

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

Then use toDouble()to get a floating point number and round as you want.

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

回答by Samuel Ives

Use .toInt()for int .toFloat()for float and .toDouble()for double

使用.toInt()对于int.toFloat()浮法和.toDouble()

toInt();

toInt();

回答by Jaziri Rami

You can use:

您可以使用:

QString str = "10";
int n = str.toInt();

Output:

输出:

n = 10

回答by Angie Quijano

As a suggestion, you also can use the QChar::digitValue()to obtain the numeric value of the digit. For example:

建议您也可以使用QChar::digitValue()来获取数字的数值。例如:

for (int var = 0; var < myString.length(); ++var) {
    bool ok;
    if (myString.at(var).isDigit()){
        int digit = myString.at(var).digitValue();
        //DO SOMETHING HERE WITH THE DIGIT
    }
}

Source: Converting one element from a QString to int

来源:将一个元素从 QString 转换为 int

回答by user3712651

On the comments:

关于评论:

sscanf(Abcd, "%f %s", &f,&s);

Gives an Error.

给出一个错误。

This is the right way:

这是正确的方法:

sscanf(Abcd, "%f %s", &f,qPrintable(s));