PDA

View Full Version : adding up numbers from text file



macaddy
15th November 2015, 23:41
I'm new to QT and C++ so this might be simple enough but it's got me totally stuck!

I'm just wanting to load a text file, split it in to arrays, add up the arrays and put the totals into a textedit.

the file is structured like this num1/num2/num3 e.g :
1/4/7
2/5/8
3/6/9

So I want to do 1+2+3 = 6 (put 6 in to text edit)



{
QString fileName = "/home/sss.txt";
QFile mFile(fileName);
mFile.open(QFile::ReadOnly | QFile::Text);
QTextStream stream(&mFile);
QString line;
do {
line = stream.readLine();
QStringList parts = line.split("/", QString::KeepEmptyParts);
if (parts.length() == 3) {
QString aa = parts[0];
QString ab = parts[1];
QString ac = parts[2];
int a, sum;
sum = 0;
int arraya[] = {aa.toInt()};

for (a=0; a<1; a++)
{
int totala = sum+=arraya[a];
QString suna = QString::number(totala);
ui->textEdit->append(suna);
}

}
} while (!line.isNull());
}


What I can't figure out is how to add the numbers together! I thought it would be simple enough but I've been googling for more than a week and experimenting with different things but am just getting more frustrated with it!

Any help would be much appreciated. Thanks.

ImaRebel
16th November 2015, 02:44
convert qstring into std::string and then use std::stoi .

anda_skoa
16th November 2015, 09:03
convert qstring into std::string and then use std::stoi .

macaddy already got ints, converting to a different string won't help anything.
But the posted code is indeed quite confusing.

So the goal is to get the sum of all numbers in the first "column", right?
In order to make a sum across the iterations of the loop, the sum variable has to be declared outside the loop.

And no need for temporary single element arrays. A single int fits nicely into a single int variable :)

Cheers,
_

macaddy
17th November 2015, 19:10
Thanks for the reply imarebel and thanks for the advice anda. I can understand the code looking confusing, it kind of morphed in to that over time as i got more confused and desperate.

Is there any site you can point me to or give me an example so I can work this out myself? Up until now I've learned as I went along but inspite of literally searching google for over a week I haven't really found anything that has helped. Thanks

d_stranz
18th November 2015, 00:44
If all you want is the sum of the numbers in the *first* column, try this:



int sumCol0 = 0;
do {
line = stream.readLine();
QStringList parts = line.split("/", QString::KeepEmptyParts);
if ( parts.length() >= 1 ) {
sumCol0 += (parts[0]).toInt();
}
} while (!line.isNull());

ui->textEdit->setText( QString::number( sumCol0 ) );


You should be able to figure out how to extend this if you want sums for each column. Do you understand why the declaration and initialization of sumCol0 is *outside* the loop that reads each line?