i want read this file and write as array to calculate average of age, classification:
"name age classificacion at school
john 21 10
maria 25 20
ricky 30 8"
but i can't make the sum because i think de program dont func because the characters in the first line, but if a put string dont calculate because the progm dont read the numbers as "numbers". What i make? i can't change the txt file
struct student
{
std::string name;
int age;
int classification;
};
//...
std::ifstream input(/*...*/);
constint NUM = 4;
student data[NUM];
int pos = 0;
// ↓overflow check ↓Check stream state, do not check for EOF. It does not work as you think.
while(pos < NUM && input >> data[pos].name >> data[pos].age >> data[pos].classification)
; //You do not do anything else in your code so body is empty
You actually do not need an array to calculate averages, you can count everything on fly:
1 2 3 4 5 6 7 8 9 10 11 12
int sum_age = 0;
int sum_class = 0;
int count = 0;
std::string dummy;
int age, class;
while(input >> dummy >> age >> class) {
sum_age += age;
sum_class += class;
++count;
}
std::cout << "Average age = " << static_cast<double>(sum_age)/count << '\n' <<
"Average classification = " << static_cast<double>(sum_class)/count << std::endl;
This is for a school work and yet i didn't learn struct, there is another way?
I also don't understand the command "static_cast<double>", can explain me or help me to find another solution?
This is possible with getline?
Thanks a lot
i made this:
[/code]
double name[60];
double age[60];
double class[60];
ifstream infile;
infile.open("stat.txt");//open the text file
if (!infile)
{
cout << "Unable to open file";
exit(1); // terminate with error
}
i=0;
while (!infile.eof())
{
infile >>name[i] >> age[i] >> class[i];
i++;
}
for (x=0;x<2;x++)
cout<<name[x]<<"\t"<< age[x] << "\t" << class[x]<<"\t"<<endl;
infile.close();
[/code]
This only func if i remove the first line of the file( "name age ...") but i cant remove the first row. How can i do?