lundi 30 mars 2020

Display names when input text is separated by # in C++?

So, input text of list.txt file is in the form: FirstName LastName#Age My task is to read the list.txt file of four lines of the above form, and output the name with the largest age. I will write my solution below, which works, but only if # is removed and inputs are separated by space. Not sure how to do it with the # being present? I understand i can use getline(), just not sure how? Eg: Alpha Beta#22 Gama Delta#10 and the output should be the name of the oldest person followed by his age. Please orient me towards a an actual correct solution. Thank you in advanceee! :)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream ins;   // declare an input file stream object

    ins.open("list.txt");  // open the file
    if (ins.fail()) {     // check if there was an error
        cout << "Error opening file";
        return -1;
    }

    string maxName;   // 
    int maxAge = 0; // 



    for (int i = 0; i < 4; i++) {   // read four lines from the file
        string firstName, lastName;
        int age;
        ins >> age;  // read three variables from the stream line

        if (nr > maxAge) {   // update the current maximum if greater
            maxAge = age;
            maxName = firstName + " " + lastName;
        }
    }

    ins.close();   // close the file

    cout << " The oldest person is: " << maxName
        << " : " << maxAge << endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire