Search code examples
c++qtfor-loopsumqstringlistmodel

Incorrect sum in for loop Qt c++


Following c++ code in qt is used by me to add values to an integer(initial value 10) and store it in a QStringList. But when I print the values of the StringList on to 3 labels it prints 10 on all lables though it should be 20,30 and 40 since I increment a by 10 through the for loop!

void MainWindow::on_pushButton_clicked()
{
    QStringList array;
    int a =10;
    for(int i=0;i<10;i++){
        a=+10;
        array<<QString::number(a);
    }
    ui->label->setText(array[0]);
    ui->label_2->setText(array[1]);
    ui->label_2->setText(array[2]);
}

How can I correct this?


Solution

  • You are using

    a =+ 10;
    // equivalent to
    a = +10;
    

    That means you are assigning 10 to a.

    You need to use the form below to increment it by 10:

    a += 10;