Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How can i convert a single character in a QString into an integer ?



  • Let me explain with the help of an example:-

    say i have this QString :

    int num = 0 ;
    QString test = "1A52D" ;
    

    and i want to convert a single character in a string ( say 2 ) into an integer so that the integer variable 'num' should store 2 in it.

    this is what i do:

    int num = 0 ;
    QString test = "1A52D" ;
    QString test123 = test[3] ;
    num = test123.toInt() ;
    

    when i run that code i get this error message :

    "conversion from QCharRef to non-scalar type QString required"



  • QString test = "1A52D" ;
    int test123 = test[2].digitValue();



  • Hi,
    @Ahti

    The below link might be useful to you.

    https://forum.qt.io/topic/14739/converting-one-element-from-a-qstring-to-int-solved/6

    which converts a character of a string to int.

    Thanks,



  • With your example you have taken
    QString stringValue = "1A52D" ;

    Sample Code:

      QString stringValue = "1A52D" ;
       int num = 0 ;
      QStringList listStr;
    
    for (int var = 0; var < stringValue.length(); ++var) {
        if (stringValue.at(var).isDigit()){
            int StringValue = stringValue.at(var).digitValue();
            qDebug () << "firstDigit" << StringValue << endl;
            listStr.append(QString::number(StringValue));
        }
    }
    

    Iterate and get the numeric values and add to StringList then get the values from StringList convert to int.

    QString oneValue  = listStr.value(0);
    QString twoValue  = listStr.value(0+1);
    QString threeValue  = listStr.value(0+2);
    
    qDebug() << " value" << oneValue << twoValue << threeValue <<  endl;
    
    qDebug() <<  oneValue.toInt();
    qDebug() <<  twoValue.toInt();
    qDebug() <<  threeValue.toInt();
    

    Assign which number you want to variable num.


Log in to reply