ChatGPT解决这个技术问题 Extra ChatGPT

How to convert QString to int?

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

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

QString Abcd = "123.5 Kb"
sscanf("123.5 Kb", "%f %s", &f,&s);
QString Abcd = "123.5 Kb"; float f; QString s; sscanf(Abcd, "%f %s", &f,&s); Error: Cannot convert "QString" to "const char*" for argument "1" to "int sscanf(const char*, const char*, ...)"
123.5 is not an integer (even without the Kb) - are you sure you want that?

N
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.

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.

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

Although this answer is ok for the specific example of the asker, I'm missing the success test of @Mikhail's answer, which should always be checked.
Yes. That’s correct. It’s an one liner. But yes one should always verify such operations
M
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

G
Grijesh Chauhan

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().

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


R
Rick

You can use:

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

Output:

n = 10

the same as most answers propose, for me it is a redundant response.
S
Stanislav Mekhonoshin

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

toInt();


A
Angie Quijano

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

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


u
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));

OP is asking about Qt, and sscanf is not Qt
Regardless of whether sscanf is the Qt way or not, this is just hideous! qPrintable returns an array of the current size of the string. The operation is undefined if the part of the string in Abcd is longer than its current value - buffer overflows. Here be dragons.