I'm somehow a n00b in C++ but i was writing a small code where i want to store user data in the elements of an array, and then when it is stored i want to count them all up together. But i can think off another way then like this:
y = (money[0].dalasis)+(money[1].dalasis)+(money[3].dalasis)
+(money[4].dalasis)+(money[5].dalasis)+(money[6].dalasis)
+(money[7].dalasis)+(money[8].dalasis);
but is there a way to use a loop for this? does anybody know a solution? I will put here my entire code till so far. Theres no errors in the code but it doesnt yet include everything i want, but only mind about the part counting up the elements of the array.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MONEY 40
#define MINUTES 40
struct amount_time {
int time;
int dalasis;
} money [MONEY], minutes [MINUTES];
int main ()
{
string mystr;
int i,n,y;
cout << "Enter the amounts and time earnt today: ";
for (i=0; i<MINUTES; i++)
{
cout << "Enter time: ";
getline (cin,mystr);
stringstream(mystr) >> minutes[i].time;
if (minutes[i].time == 0)
{
i = 40;
}
}
for (n=0; n<MONEY; n++)
{
cout << "Enter Amount: ";
getline (cin,mystr);
stringstream(mystr) >> money[n].dalasis;
if (money[n].dalasis == 0)
{
n = 40;
}
}
y =(money[0].dalasis)+(money[1].dalasis)+(money[3].dalasis)+(money[4].dalasis)+(money[5].dalasis)+(money[6].dalasis)+(money[7].dalasis)+(money[8].dalasis)+(money[9].dalasis)+(money[10].dalasis)+(money[11].dalasis)+(money[12].dalasis)+(money[13].dalasis)+(money[14].dalasis)+(money[15].dalasis)+(money[16].dalasis);
cout << y;
cin.get();
cin.get();
return 0;
}
Hmm unfortunatly it doesnt work, cause when i use this code i get a long number 13645578 or something like that, instead of adding the numbers together. I also tried some similar codes but in some way i cannot get it working. But thanks for the reply anyway :) Maybe someone has another idea?
Today i tried something myself but somehow i keep getting a segmentation fault.
1 2 3 4 5 6 7 8
for (k = 0; k < 40; (k+2))
{
if (k > 0)
{
b = (k-1);
}
y = (money[b].dalasis)+(money[k].dalasis);
}
In this way i thought maybe "k" will everytime be money[0].dalasis and money[2].dalasis and money[4].dalasis etc etc and then "b" will be money[1].dalasis, money[3].dalasis etc etc but it also doesnt work with the segmentation fault.
I was also thinking when i store money[b].dalasis + money[k].dalasis in "y" won't it replace the number everytime then? for example money[0].dalasis + money[1].dalasis is 30, and in the next loop money[2] + money[3]= 45. Will it not replace the value 30 with value 45 in the "y" variable in stead off adding them together?