# Introduction to Files - Exercise 2 - Sample Answer

Program | Comments
    #include <iostream>
    #include <string>
| The required include files. The string header file is required since the program uses the string class.
    int main()
    {
     string m, u, h, ldate, log_msg;
     int i,j,k;
| A number of string variables are declared and not initialised. These will hold the different parts of the output line. The integer variables are used to hold the results of string finds.
     while (getline(cin,m))
      { i = m.find("(");
        j = m.find(")");
        k = m.find("tty");
        u = m.substr(0, k - 1);
        ldate = m.substr(18,12);
| The variables i and j indicate if the line from who contains a host name. Since the host name is inside ()'s we search for these and get the relevant positions in i and j. The variable k is used to determine where the user field ends. It is used when string u is assigned the user substring from m the input line from who. The log on date and time are copied from m to ldate.
       if (i != string::npos)
        h = "logged on from host " +
            m.substr(i + 1, j - 1 - i);
       else
        h = "logged on locally";
       log_msg = h + " on " + ldate;
| If there is host name in the who output then i + 1 has the starting position, j - 1 has the end position. The expression j - 1 - i gives the length of the host name.
       cout << "USER " + u
            << log_msg
            << endl;
      }

     return 0;
    }
| Last of all the program outputs the modified string.

Return to lesson

Copyright © 1999 - 2001 David Beech