从QString中提取整数

Extracting Integers from QString

本文关键字:整数 提取 QString      更新时间:2023-10-16

我需要帮助从QT QString获取一些整数。我有一个文件,并且正在存储不同的行,与此类似:

Fitness: 4 123456789123456789123456789
Fitness: 3 135791357913579135791357913

....等等。首先,我试图找到最高健身的一个(在上方,"健身:4 ....." 4是健身水平(,而一个最高的健身也是如此。然后,我要浏览最高和第二高的健身,并在健身水平后将27个数字复制到2D阵列"读取"中。这些是我坚持的部分。这是我的代码:

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

任何帮助将不胜感激。预先感谢

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

您的代码中有很多错误。 indexOf返回一个int,该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"