繁体   English   中英

从QString提取整数

[英]Extracting Integers from QString

我需要帮助来从Qt QString中获取一些整数。 我有一个文件,并且要存储不同的行,类似于其中的内容:

Fitness: 4 123456789123456789123456789
Fitness: 3 135791357913579135791357913

....等等。 首先,我正在尝试找到适应度最高的那个(上面的“ Fitness: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(Highest,secHighest);

        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

任何帮助表示赞赏。 提前致谢

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

您的代码有很多错误。 indexOf返回一个int,它是找到的文本的位置;如果未找到, indexOf返回-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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM