从QString中提取整数

时间:2017-04-30 21:18:28

标签: c++ qt

我需要帮助从Qt QString中获取一些整数。 我有一个文件,我存储了不同的行,类似于此:

Fitness: 4 123456789123456789123456789
Fitness: 3 135791357913579135791357913

....等等。首先,我试图找到一个健身最高的人(在上面,在线'健身:4 ......' 4是健身水平),以及健身第二高。然后,我将通过具有最高和第二高适应度的那些,并将健身水平后的27个数字复制到2D阵列中,然后阅读' readIn'这些是我坚持的部分。这是我的代码:

void MainWindow::SpliceGenes(){
    int secHighest = 0;
    int Highest = 0;
    int howFar = 0;
    QFile file("C:/Users/Quentin/Documents/NeuralNetInfo.txt");
    if(file.open(QIODevice::ReadWrite)){
        QTextStream stream(&file);
        QString text = stream.readAll();

        while(text.indexOf(": ", howFar) != -1){//this should make sure it goes through the entire file until it's gotten all of the fitness values. 
            if(QString.toInt(text[text.indexOf(": ", howFar) + 2]) > Highest){//this should be: if the number after the ': ' is higher than the current
                 //highest fitness value...
                secHighest = Highest;
                Highest = QString.toInt(text[text.indexOf(": ", howFar) + 1]);//should be: the new highest value equals the number after the ': '

                howFar = text.indexOf(": ", howFar) + 5;//I use howFar to skip past ': ' I've already looked at. 

// 5是一个随机数,可以确保它超过了':'它刚刚开启                 }             }     //其余的并不重要(我不认为)             ReadNeuralNet(最高,最高);

        for(int i = 0; i< 3; i++){
            readIn[(qrand() % 9)] [i] = readInTwo[qrand() % 9] [i];
        }
    }
}

这些是我得到的错误:

//on 'if(QString.toInt(text[text.indexOf(": ", howFar) + 2]) > Highest){' 
error: C2059: syntax error: '.' 
error: C2143: syntax error: missing ';' before '{'

//on 'Highest = QString.toInt(text[text.indexOf(": ", howFar) + 1]);'
error: C2275: 'QString': illegal use of this type as an expression 
error: C2228: left of '.toInt' must have class/struct/union

//and on the last curly bracket
error: C1903: unable to recover from previous error(s); stopping compilation

感谢任何帮助。提前致谢

1 个答案:

答案 0 :(得分:0)

toInt()的定义是int QString::toInt(bool *ok = Q_NULLPTR, int base = 10) const,它不是静态的,这意味着你需要一个对象来处理。 textQString,因此您可以使用其.toInt()方法。

您的代码中存在很多错误。 indexOf返回一个int,它是找到的文本的位置,如果找不到则返回-1。

您可以将mid与索引(如果找到)结合使用,以剪切您要转换的部分。

最好使用readLine代替readAll并循环处理每一行QTextStream

可能的实施:

QFile file { QStringLiteral("NeuralNetInfo.txt") };

if(file.open(QIODevice::ReadOnly))
{
    auto pos { 0 };
    QString line { QStringLiteral("") };
    QTextStream stream { &file };

    while(!stream.atEnd())
    {
        line = stream.readLine();
        pos  = line.indexOf(QStringLiteral(": "));

        if(pos)
        {
            pos += 2;

            if(pos < line.length())
            {
                qDebug() << line.mid(pos , 1);
            }
        }
    }
}

输出:

"4"
"3"