Comparing Strings and Substrings

Copy the following data and paste them in a file named Payroll.txt (code#salary).

1#23400
4#17000
5#21000
6#12600
9#26700
10#18900
11#18500
13#12000
15#49000
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000
Write a program that allows the user to enter a payroll code. The program should search for the payroll code in the file and then display the appropriate salary. If the payroll code is not in the file, the program should display an appropriate message. Use a sentinel value to end the program.

So far i have this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{

string code;
string salary;
ifstream inputfile;
inputfile.open("Payroll.txt");

cout << "Hello this program will display a salary with its corresponding code number." << endl;
cout << "Please enter your code number. ";
cin >> code;

getline(inputfile,salary);
cout << salary << endl;

while (inputfile >> salary)
{


}



}

But I dont know how to compare strings in a way and loop it how the task is asking for it.
> But I dont know how to compare strings in a way and loop it how the task is asking for it.

If you want to read numbers, read numbers; favour formatted input over unformatted input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>

int main()
{
    const char* const file_name = "payroll.txt" ;

    {
        // Copy the following data and paste them in a file named Payroll.txt
        std::ofstream(file_name) << "1#23400\n 4#17000\n 5#21000\n 6#12600\n 9#26700\n 10#18900\n 11#18500\n"
                                    "13#12000\n 15#49000\n 16#56500\n 20#65000\n 21#65500\n 22#78200\n"
                                    "23#71000\n 24#71100\n 25#72000\n 30#83000\n 31#84000\n 32#90000\n" ;
    }

    int payroll_code ;
    // Use a sentinel value to end the program (sentinel == -1)
    while( std::cout << "payroll code (enter -1 to quit)? " && std::cin >> payroll_code && payroll_code != -1 )
    {
        std::ifstream file(file_name) ; // open the file for input
        int code_in_file ;
        char separator ; // separator character ( expect # )
        int salary ;

        // get to the line in the file containing this code and read it
        while( file >> code_in_file >> separator >> salary && separator == '#' && code_in_file != payroll_code ) ;

        if( code_in_file == payroll_code ) std::cout << "salary: " << salary << '\n' ;
        else std::cout << "code " << payroll_code << " was not found\n" ;
    }
}
Topic archived. No new replies allowed.