c++ programming

1. Print the entire list.
This menu item is selected by typing 1 and it should simply print the contents of the file
in suitable format on the screen. (Fields (columns) to display in output are: lastname
initial, FNPF#, age, Gross_Income and Resident)
2. Print list sorted by Gross Income
This menu item is selected by typing 2. Program then prints the list in ascending order
of Gross Income. (Fields (columns) to display in output are: FNPF# and
Gross_Income) [An algorithm to sort an array is given at the end of this project
description]
3. Print list of employees which match a given lastname initial
The user selects this option by typing 3. Then the user is asked to enter the search
initial. If there are employees who have that initial, program prints their record,
otherwise a if no students have last names matching the search initial a “no matching
record found” message is displayed. (Fields (columns) to display in output are:
lastname and FNPF#)CS111, USP – Assignment 2 S1/2021
Page 5 of 10
4.Calculate and Print in a file called IncomeTax.txt, the tax and the net income corresponding
to the provided Gross Income.
The user selects this option by typing 4. The program then calculates and prints to a
file IncomeTax.txt, the tax corresponding to the provided Gross Income and the Net
Income. The format of the resultant file is shown below (the columns are separated by
tabs)
[NB. The formula/criteria for calculating the Tax corresponding to the provided Gross
Income is given in Table 1 and the Net Income = Gross Income – Tax]
5. Exit program
User selects this option by typing 5. This is when program should end.
[Note: After each command is processed (except menu 5) program must display the
menu options again
and the specific c/c++ question is.....
Hello batzot,

If you are not aware of this:

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



keskiverto once wrote:

Please note that this is not a homework site. We won't do your homework for you. The purpose of homework is that you learn by doing. However we are always willing to help solve problems you encountered, correct mistakes you made in your code and answer your questions.

We didn't see your attempts to solve this problem yourself and so we cannot correct mistakes you didn't made and answer questions you didn't ask. To get help you should do something yourself and get real problems with something. If your problem is "I don't understand a thing", then you should go back to basics and study again.



That said start with this:

1. Print the entire list.
This menu item is selected by typing 1 and it should simply print the contents of the file
in suitable format on the screen. (Fields (columns) to display in output are:
lastname initial, FNPF#1, age, Gross_Income and Resident).

2. Print list sorted by Gross Income
This menu item is selected by typing 2. Program then prints the list in ascending order
of Gross Income. (Fields (columns) to display in output are:
FNPF# and Gross_Income) [An algorithm to sort an array is given at the end of this project
description]2

3. Print list of employees which match a given lastname initial
The user selects this option by typing 3. Then the user is asked to enter the search
initial. If there are employees who have that initial, program prints their record,
otherwise a if no students have last names matching the search initial a “no matching
record found” message is displayed. (Fields (columns) to display in output are:
lastname and FNPF#)CS111, USP – Assignment 2 S1/2021
Page 5 of 10

4.Calculate and Print in a file called IncomeTax.txt, the tax and the net income corresponding
to the provided Gross Income.
The user selects this option by typing 4. The program then calculates and prints to a
file IncomeTax.txt, the tax corresponding to the provided Gross Income and the Net
Income. The format of the resultant file is shown below (the columns are separated by
tabs)3
[NB. The formula/criteria for calculating the Tax corresponding to the provided Gross
Income is given in Table 1 and the Net Income = Gross Income – Tax]

5. Exit program
User selects this option by typing 5. This is when program should end.
[Note: After each command is processed (except menu 5) program must display the
menu options again

1. FNPF# is? Give a description and an example.
2. Provide algorithm, so there is code offered that you can not use.
3. Give some idea of the table used.

If there is an input file provide a sample or the whole file.

Provide the operating system that you are using and the IDE/compiler and version
numbers if you know them. If you know the C++ standard that the IDE/compiler is set up
to use mention that.

It also helps to have an idea of what you have studied and what you are expected
to use. This way you are less likely to get code that you can not use.


The very very 1st step is to take a piece of paper and plan the program. Without a plan you will be taking longer to write you code. As scuba-divers say:
Plan your dive and dive your plan.
The same applies to coding.

I would start with setting up to deal with #1 first. Get information into something that you can print out. With out this there is no point in trying to code for something that you can not test.

Work in small steps, compile and test the program often. Fix any errors that you can an ask about what you do not understand. When asking about an error post the full error message that the compiler gives you, so there is no misunderstanding.

When you have something post what you have done. It does not have to be the full program.

Andy
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
31
32
33
34
35
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
	
	const int SIZE = 200;
	char ln_Initial[SIZE];
	int ID[SIZE];
	int age[SIZE];
	int gross_Income[SIZE];
	char resident[SIZE];
	string discard1, discard2;
	int i = 0;
	
	string inFileName = "IncomeRec.txt";
	ifstream inFile;
	inFile.open(inFileName.c_str());
	
	if(inFile.is_open()){
		getline(inFile, discard1);
		getline(inFile, discard2);
		while(!inFile.eof()){
			inFile >> ln_Initial[i] >> ID[i] >> age[i] >> gross_Income[i] >> resident[i];
			cout << endl << ln_Initial[i] << " " << ID[i] << " " << age[i] << gross_Income[i] << " " << resident[i];
			i++;
		}			
		inFile.close();
	}else{
		cout << "Error file not open." << endl;
	}
	return 0;
}[code]
[/code]
Last edited on
this is what i've done so far and the part that i'm looking is how to input 1 and display the entire list
Hello batzot,

Looking over your code these are my suggestions:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <string>

#include <fstream>

using namespace std;  // <--- Best not to use.

int main()
{
    const int SIZE{ 200 };

    char ln_Initial[SIZE]{};  // <--- ALWAYS initialize all your variables.
    int ID[SIZE]{};
    int age[SIZE]{};
    int gross_Income[SIZE]{};
    char resident[SIZE]{};
    string discard1, discard2;  // <--- Strings are empty when defined and do not need initialized.
    int i{};

    string inFileName = "IncomeRec.txt";
    ifstream inFile(inFileName);  // <--- Can be done at the same time.
    //inFile.open(inFileName.c_str());

    if (!inFile)
    {
        //std::cout << "\n     File " << std::quoted(inFileName) << " did not open.\n";  // <--- Requires header file "<iomanip>".
        std::cout << "\n     File \"" << inFileName << "\" did not open.\n";

        return 1;  // <--- Can be any number other than (0)zero.
        // Or
        //return std::cout << "\n     File \"" << inFileName << "\" did not open.\n", 1;
    }

    if (inFile.is_open())
    {
        getline(inFile, discard1);
        getline(inFile, discard2);

        while (!inFile.eof())
        {
            inFile >> ln_Initial[i] >> ID[i] >> age[i] >> gross_Income[i] >> resident[i];
            cout << endl << ln_Initial[i] << " " << ID[i] << " " << age[i] << gross_Income[i] << " " << resident[i];

            i++;
        }

        inFile.close();
    }
    else
    {
        cout << "Error file not open." << endl;
    }

    return 0;  // <--- Not required, but makes a good break point for testing.
}

Line 21 is the more accepted way to make use of the language to define a file stream and use the overloaded ctor to open the file at the same time. You will see more examples of code like this in the future.

I changed your if statement. Should this become true deal with an error message and leave the program there not later.

if(inFile.is_open()). To be blunt it is kind of tacky to run the whole "main" function on an if/else statement. And with the revised if statement you do not need this. The other problem is that your file stream may be open until you close it, but may still not be usable. I would look at it as if you need this if statement then you did something wrong.

The while loop at line 39 does not work the way that you are thinking. You are checking if "eof" has been set before you read the file which may set "eof", but since you are in the loop you will process 1 additional record that may have the values in the variables from the last read or they could be empty, numeric variables set to (0)zero and strings set to empty, either way "i", in this case needs a better name, would be 1 more than it should be. Then after the while loop you will realize that you have to subtract 1 from "i" so it will have the correct value.

The more preferred way is: while (inFile >> ln_Initial[i]) or you could put the entire read line in the condition that way if any part fails the entire condition fails.

You do not need lines 34 and 35 along with lines 48 to 52.

Your variable ln_Initial is fine, but in some fonts the lower case (L) can be mistaken for the number (1). The same occurs with the letter O and the number (0)zero. in some fonts it may be hard to tell the difference.

Another suggestion is instead of all those arrays create 1 struct to hold all the variables an 1 array of structs to hold the information. If you have studies vectors that would be even better. You will have to mention that.

You also need to mention if you have covered functions yet. The program would be greatly improved if you can use functions.

Once you have read the file into whatever you are going to use you could write the code to print the array which would be moved later as the program grows.

Next I would work on the menu that you will need. Do not worry about menu choices that you have not coded for yet just get it to display the menu with al possible choices first. And since the first choice would be print this is where you would move the code to that prints out the array or use a function call to call the print function.

This is a good reason to rename "i" to something useful like: "amtOfArrayUsed", "count" or anything else that describes what the variable is used for. These are suggestions the choice is up to you, but do not use a single letter for the variable.

Single letter are fine for for loops as the variable is local to the loop and is destroyed when the loop is finished.

Since you did not provide any idea of the input file it is hard to test the program. Any file I create may not be the same as your file. Therefor the code to read the file may work for what I have, but not on the file you are using.

Andy
Hii Andy this the file:


Lastname(initial) FNPF# Age Gross_Income Resident
-------------------------------------------------
F 12345 24 40000 Y
B 12361 19 20000 Y
H 34763 47 100000 N
H 11224 50 35000 Y
R 54129 35 75000 N
B 10717 26 280000 Y
Andy , no i havent studies vectors please provide me any notes that i should study
the program should do like this:
if the user input 1 then it will print the entire list
if 2 then it will print the list in ascending order of Gross Income
if 3 then Print list of employees which match a given lastname initial
4. Calculate:
a) the Tax corresponding to the provided gross income of each employee using Table 1; and
b) the Net Income and
c) Print in a file called IncomeTax.txt where the tax and Net income are displayed in separate columns.
[NB. The tax is calculated according to the Tax Calculation Table provided
and the Net Income = Gross income – Tax]
5. Exit program.

but this is what i been done so far:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
	cout << "\t\t\tINCOME RECORDS OF EMPLOYEES IN A FIRM\n";
	cout << "\t\t\t-------------------------------------\n"; 
	
	const int SIZE = 200;
	char ln_Initial[SIZE];
	int ID[SIZE];
	int age[SIZE];
	int gross_Income[SIZE];
	char resident[SIZE];
	string discard1, discard2;
	int i = 0;
	
	char opt1 = 1;
	char opt2 = 2;
	
	//Choose and input an option to display your needs
	cout << "Choose from the following Options: " << endl;
	cout << "1) To Diplay the entire list " << endl;
	cout << "2) To Display the list in the Ascending order of Grosss Income" << endl;
	cout << "OPTION: ";
	cin >> opt1 >> opt2;
	
	//File
	string inFileName = "IncomeRec.txt";
	ifstream inFile;
	inFile.open(inFileName.c_str());
	
	if(inFile.is_open() && !opt2){
		getline(inFile, discard1);
		getline(inFile, discard2);
		while(!inFile.eof()){
			inFile >> ln_Initial[i] >> ID[i] >> age[i] >> gross_Income[i] >> resident[i];
			cout << "Lastname(initial)" << " FNPF# " << "Age " << " Gross Income " << " Resident" << endl;
			cout << endl << ln_Initial[i] << " " << ID[i] << " " << age[i] << gross_Income[i] << " " << resident[i];
			i++;
		}			
		inFile.close();
	}else if(!opt1){
		
		
		
		
	}else{
		cout << "Error file not open." << endl;
	}
	return 0;
}
Hello batzot,

I will go over this in more detail in the morning, but for now.

"opt1" should be an "int" not a "char" and a better name could be "menuChoice". I see no use for "opt2" at this time.

Line 28 is asking for 2 inputs, but the menu tends to imply only 1 input.

Line 35 is likely to always be false.

Line 38 will give you 1 extra element in your array and "i" will be 1 more than it should be. But since the if statement is more likely to be false you will never reach the while loop, so you will never see the problem.

Reading the file should be done before you present the menu not after.

If you do not want to answer my questions that is fine, but be prepared for code and program examples that are beyond what you have learned.

Do you know how to use functions?
Have you studied structs?
If this is a school assignment what is the focus of the assignment? Using multiple arrays? or something else.

There are better ways to write your program, but I will not force that upon you. I can work with what you know, but I need to know what that is first.

Andy
Hello batzot,

For the most part I just rearranged your program, but I did also make a few changes to start with just to make it run properly.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>

#include <fstream>

using namespace std;

int main()
{
    const string inFileName = "IncomeRec.txt";  // <--- Changed.

    ifstream inFile(inFileName);  // <--- Changed.
    //inFile.open(inFileName.c_str());

    if (!inFile)
    {
        return std::cout << "\n     File \"" << inFileName << "\" did not open.\n", 1;
    }

    constexpr int SIZE{ 15 };       // <--- Org 200. Changed.

    char ln_Initial[SIZE];  // <--- ALWAYS initialize all your variables.
    int ID[SIZE];
    int age[SIZE];
    int gross_Income[SIZE];
    char resident[SIZE];
    string discard1/*, discard2*/;  // <--- Strings are empty when defined and do not need initialized.
    int recordCount{};          // <--- Changed.

    getline(inFile, discard1);  // <--- You only need 1 string that can be reused.
    getline(inFile, discard1);

    while (!inFile.eof())  // <--- Does not work the way that you think it does.
    {
        inFile >> ln_Initial[recordCount] >> ID[recordCount] >> age[recordCount] >> gross_Income[recordCount] >> resident[recordCount];

        //cout << "Lastname(initial)" << " FNPF# " << "Age " << " Gross Income " << " Resident" << endl;

        //cout << endl << ln_Initial[recordCount] << " " << ID[recordCount] << " " << age[recordCount] << gross_Income[recordCount] << " " << resident[recordCount];

        recordCount++;
    }

    inFile.close();

    cout <<
        "\n"
        "\t\t\tINCOME RECORDS OF EMPLOYEES IN A FIRM\n"
        "\t\t\t-------------------------------------\n\n";

    int menuChoice{};  // <--- Changed.
    char opt2 = 2;

    //Choose and input an option to display your needs
    cout <<
        "Choose from the following Options:\n"
        "1) To Display the entire list\n"  // <--- Spelling correction "Diplay".
        "2) To Display the list in the Ascending order of Gross Income\n"  // <--- Spelling correction gross has to many "s"
        "OPTION: ";
    cin >> menuChoice/* >> opt2*/;  // <--- Changed.

    //File
    //if (inFile.is_open() && !opt2)  // <--- Not needed.
    //{

    //}

    if (menuChoice == 1)
    {
        // Code for choice 1.
        // Use a for loop to print each record. Initial code already in the read while loop.

        }
    }
    else if (menuChoice == 2)
    {
        // Code for choice 2.
    }

    return 0;  // <--- Not required, but makes a good break point for testing.
}

"main" starts by opening the file stream and checking it. Should the if statement be true you leave the program and fix the problem. Everything after that is pointless until the file stream is open and usable.

Should the if statement be false then you can set up your variables and read the file.

Based on your code and while(!inFile.eof()) this is the output I get:

                        INCOME RECORDS OF EMPLOYEES IN A FIRM
                        -------------------------------------
Choose from the following Options:
1) To Display the entire list
2) To Display the list in the Ascending order of Grosss Income
OPTION: 1

F 12345 2440000 Y  // <--- needs a space or 2 betwenn the 24 and 40000.
B 12361 1920000 Y
H 34763 47100000 N
H 11224 5035000 Y
R 54129 3575000 N
B 10717 26280000 Y
╠ -858993460 -858993460-858993460 ╠


The last line is what you get when you do not initialize your variables and with the while loop of while(!inFile.eof()). As you can see the while condition is not working the way that you are thinking or want.

I can see a potential problem with choice 2. It will be much more work sorting the "gross_Income" array and keeping all the rest in sync. This is where a struct and an array of structs would be more useful.

Last night I played with using a struct and it worked out very well.

The if/else if statements near the end of the program will give you an idea of what you can do. A switch would work better if you have studied that.

Andy
Hello batzot,

Forgot to mention that you do not need a "cout" and "endl" for each line that you need to print to the screen or a file.

setting up the menu like this:
1
2
3
4
5
6
    cout <<
        "\n"
        "Choose from the following Options:\n"
        "1) To Display the entire list\n"
        "2) To Display the list in the Ascending order of Grosss Income\n"
        "OPTION: ";

The 5 lines of quoted strings may seem separate, but it is considered 1 big string. it would look more like this to the compiler:
 
cout << "\nChoose from the following Options:\n1) To Display the entire list\n2) To Display the list in the Ascending order of Gross Income\nOPTION: ";

They both work the same, but which is easier to read and work with. In the 1st example it is easier to add to or edit the code when needed, such as:
1
2
3
4
5
6
7
    cout <<
        "\n"
        "Choose from the following Options:\n"
        "1) To Display the entire list\n"
        "2) To Display the list in the Ascending order of Grosss Income\n"
        "5) Exit\n"
        " Enter choice: ";

When you get to it adding 3 and 4 is very easy.

And be careful with using "\t". At the beginning of a string it is not usually a problem, but in the middle of a string it may not space as you would want.

Andy
As a first revision, consider:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <iomanip>

struct Employee {
	char init {};
	int id {};
	unsigned age {};
	unsigned gross {};
	char resid {};
};

std::istream& operator>>(std::istream& ifs, Employee& emp)
{
	return ifs >> emp.init >> emp.id >> emp.age >> emp.gross >> emp.resid;
}

void display(const Employee employees[], size_t recCnt)
{
	std::cout << '\n' << std::left << std::setw(9) << "Initial" << std::setw(7) << "FNPF#" << std::right << std::setw(6) << "Age"
		<< std::setw(9) << "Gross" << std::setw(10) << "Resident\n";

	for (size_t i = 0; i < recCnt; ++i) {
		const auto& e {employees[i]};

		std::cout << std::left << std::setw(9) << e.init << std::setw(7) << e.id << std::setw(5) << std::right << e.age
			<< std::setw(10) << e.gross << std::setw(6) << e.resid << '\n';
	}

	std::cout << '\n';
}

int main()
{
	constexpr const char* const inFileName {"IncomeRec.txt"};
	constexpr size_t empSize {200};

	std::ifstream inFile(inFileName);

	if (!inFile)
		return (std::cout << "\n     File \"" << inFileName << "\" did not open.\n"), 1;

	std::string discard;
	int recordCount {};

	getline(inFile, discard);
	getline(inFile, discard);

	Employee employees[empSize] {};

	for (Employee emp; recordCount < empSize && inFile >> emp; employees[recordCount++] = emp);

	std::cout << "\n\tINCOME RECORDS OF EMPLOYEES IN A FIRM\n"
		<< "\t-------------------------------------\n\n";

	for (int menuChoice {1}; menuChoice; ) {
		std::cout << "Choose from the following Options:\n"
			<< "1) To Display the entire list\n"
			<< "2) To Display the list in the Ascending order of Gross Income\n"
			<< "0) Quit\n\n"
			<< "OPTION: ";

		std::cin >> menuChoice;

		switch (menuChoice) {
			case 1:
				display(employees, recordCount);
				break;

			case 2:
				std::sort(employees, employees + recordCount, [](const auto& e1, const auto& e2) { return e1.gross < e2.gross; });
				display(employees, recordCount);
				break;

			case 0:
				break;

			default:
				std::cout << "Invalid option\n";
				break;
		}
	}
}




        INCOME RECORDS OF EMPLOYEES IN A FIRM
        -------------------------------------

Choose from the following Options:
1) To Display the entire list
2) To Display the list in the Ascending order of Gross Income
0) Quit

OPTION: 1

Initial  FNPF#     Age    Gross Resident
F        12345     24     40000     Y
B        12361     19     20000     Y
H        34763     47    100000     N
H        11224     50     35000     Y
R        54129     35     75000     N
B        10717     26    280000     Y

Choose from the following Options:
1) To Display the entire list
2) To Display the list in the Ascending order of Gross Income
0) Quit

OPTION: 2

Initial  FNPF#     Age    Gross Resident
B        12361     19     20000     Y
H        11224     50     35000     Y
F        12345     24     40000     Y
R        54129     35     75000     N
H        34763     47    100000     N
B        10717     26    280000     Y

Choose from the following Options:
1) To Display the entire list
2) To Display the list in the Ascending order of Gross Income
0) Quit

OPTION: 0

Topic archived. No new replies allowed.