Hey i'm new to programming. I am coding in c++ and have to make a program that reads names and their age, add the sum of all ages then display it. Which works. But the second part of the task is to code it so you can add the names to the text file and the program reads that aswell.
The names are in a text file like this:
Marie Sten
29
Alexander Lind
35
Olle Ibrahimovic
30
Kajsa Persson
35
Peter Andersson
27
James Andersson
30
Now Peter and James Andersson are the names i've added but when i try to read the file those two are not counted or displayed.
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::string namn;
int age;
std::ifstream fil("elevinfo.txt");
std::getline(fil, namn); // namn --> Marie Sten
fil >> age; // age --> 29
int sum = 0;
int antal = 0;
while(fil.good())
{
antal++; // antal --> 1
sum += age; // sum --> 29
std::cout << namn << ": " << age << '\n'; // Marie Sten: 29
fil.ignore();
std::getline(fil, namn); // namn --> Alexander Lind
fil >> age; // age --> 35
}
fil.close();
std::cout << sum/antal << '\n';
return 0;
}
Thank you soo much for you help. Sorry for the late answer, i've been working. But i'm still having some issues. Thomas1965, i tried you code just out of curiosity but it still didn't work.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
bool getData( istream &strm, string &name, int &age )
{
if ( !getline( strm, name ) ) returnfalse; // attempt to read a name (may be blank line)
while( name.find_first_not_of( " " ) == string::npos ) // repeat if line is blank (or newline not fed after >> operation)
{
if ( !getline( strm, name ) ) returnfalse;
}
strm >> age; // presumes that successful read of name means age is OK
returntrue;
}
int main()
{
string name;
int age;
int sum = 0, antal = 0;
ifstream fil( "elevinfo.txt" );
while( getData( fil, name, age ) )
{
antal++;
sum += age;
cout << name << ": " << age << endl;
}
fil.close();
cout << "Count: " << antal << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << (double)sum / antal << endl;
return 0;
}
Marie Sten: 29
Alexander Lind: 35
Olle Ibrahimovic: 30
Kajsa Persson: 35
Peter Andersson: 27
James Andersson: 30
Count: 6
Sum: 186
Average: 31
It would be useful to put name and age in a struct, then overload >> for this struct.