user3326689
user3326689

Reputation: 53

Printing strings and integers from a text file (C++)

I have to read from a text file that contains strings and integers and write a program that finds the oldest person and displays their name. This is what is on my text file

Jefferson 17
Bill 24
Mary 19
Jack 22
Matthew 19
Claudia 23
Judy 18

I am having trouble printing the name of the oldest person once I find what the oldest age is. Can anyone walk me through it?

Upvotes: 0

Views: 147

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

Unless this is a school assignment, where you have to implement the algorithms yourself, it's actually very easy to solve everything using the standard C++ library:

First you read each line using std::getline into a std::string instance.

With this string and std::istringstream you can then parse out the different fields using the normal input operator >>.

You can store the data in a std::map, with the age as the key and the name as the data. As std::map is sorted on key, the last entry in the map is the "oldest" person.

If there can be multiple persons with the same age, then you need to use std::multimap instead, and be ready to print multiple persons with the same age.

Upvotes: 1

herohuyongtao
herohuyongtao

Reputation: 50667

You can simply store them into a vector<pair<string, int>> to associate names with their ages together. Once you find where the oldest age is, you find its name.

If you store them in two separate vectors, make sure you keep tracking of them synchronously.


Updated: For your code (as you commented below), you should change

for(int i=1; i<=7;++i) 
{ 
    if(age[i]>max) 
        max=age[i]; 
    name[i]=max; 
    ...
} 

to

string name_oldest;             // to store the oldest name
for(int i=1; i<=7;++i) 
{ 
    if(age[i]>max) 
    {
        max=age[i]; 
        name_oldest = name[i];  // update here
    }
    ...
} 

Upvotes: 1

Related Questions