• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 01:50
CEST 07:50
KST 14:50
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL20] Ro16 Preview Pt1: Ascent8Maestros of the Game: Week 1/Play-in Preview12[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4
Community News
LiuLi Cup - September 2025 Tournaments2Weekly Cups (August 25-31): Clem's Last Straw?39Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris64Weekly Cups (Aug 11-17): MaxPax triples again!15
StarCraft 2
General
Weekly Cups (Sept 1-7): MaxPax rebounds & Clem saga continues Production Quality - Maestros of the Game Vs RSL 2 #1: Maru - Greatest Players of All Time Team Liquid Map Contest #21 - Presented by Monster Energy Geoff 'iNcontroL' Robinson has passed away
Tourneys
Maestros of The Game—$20k event w/ live finals in Paris Sparkling Tuna Cup - Weekly Open Tournament RSL: Revival, a new crowdfunded tournament series Chzzk MurlocKing SC1 vs SC2 Cup Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
External Content
Mutation # 490 Masters of Midnight Mutation # 489 Bannable Offense Mutation # 488 What Goes Around Mutation # 487 Think Fast
Brood War
General
Exploring the Bold World of Mike Tyson Vape Flavor ASL20 General Discussion BSL Polish World Championship 2025 20-21 September [ASL20] Ro16 Preview Pt1: Ascent BGH Auto Balance -> http://bghmmr.eu/
Tourneys
[ASL20] Ro16 Group A [IPSL] ISPL Season 1 Winter Qualis and Info! [Megathread] Daily Proleagues Is there English video for group selection for ASL
Strategy
Simple Questions, Simple Answers Muta micro map competition Fighting Spirit mining rates [G] Mineral Boosting
Other Games
General Games
Stormgate/Frost Giant Megathread General RTS Discussion Thread Nintendo Switch Thread Path of Exile Warcraft III: The Frozen Throne
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread The Games Industry And ATVI Things Aren’t Peaceful in Palestine UK Politics Mega-thread Russo-Ukrainian War Thread
Fan Clubs
The Happy Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion MLB/Baseball 2023 2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread High temperatures on bridge(s)
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
Collective Intelligence: Tea…
TrAiDoS
A very expensive lesson on ma…
Garnet
hello world
radishsoup
Lemme tell you a thing o…
JoinTheRain
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
INDEPENDIENTE LA CTM
XenOsky
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1206 users

Can anyone help me with basic C++?

Blogs > Rain
Post a Reply
Rain
Profile Blog Joined July 2011
120 Posts
Last Edited: 2015-03-17 03:47:12
March 17 2015 03:43 GMT
#1
Hi This is former progamer Fnatic.Rain (TSL.Rain). I'm currently taking my very first programming class and I only know a few things about C++.
I'm currently working on my Assignment and I'm kind of lost right now..



This is my main function. What I have to do is to separate this main function into modules.
(objected oriented method) I tried this million times and it doesn't seem to work..




Main
+ Show Spoiler +
Data Design Scheme
Declare lastName,firstName, fullName as string
Declare payrate,hours,gros,tax,net as real
Declare answer as character
Declare empCounter as integer
Declare reportFile as file
*/

#include <stdio.h> // for printf() and scanf()
#include <string.h> // for strcpy() and strcat()
#include <stdlib.h> // for exit()
#define addr(var) &var
#define REPORTHEADINGS " Employee Pay Hours Gross Tax Netn"
#define REPORTHEADINGS2 " Name Rate Worked Pay Amount Payn"
#define REPORTLINE " ======== ==== ====== ===== ====== ======/n"
#define format " %-23s%8.2f%10.2f%10.2f%8.2f%10.2fn"
#define TAXRATE 0.15
#define OVERTIMERATE 1.5
#define BLANKSPACE " /n"


int main(void) // main function HEADER
{

char lastName[15+1]; // max length is 15 characters
char firstName[10+1]; // max length is 10 characters
char fullName[15+10+2+1];
float payrate,hours,gross; // variables declaration section
float tax,net;
float payratetotal,hourstotal,grosstotal,taxtotal,nettotal;
float avgpayrate,avghours,avggross,avgtax,avgnet;
char answer;
int empCounter;
FILE * reportFile; // read "reportFile is a pointer to a file "

reportFile = fopen("c:tempmyReport.txt","wt");
if (reportFile == NULL)
{
printf(" ... it did not create the report file ... exiting applicationn");
fflush(stdin);
getchar();
exit(100);
}
empCounter = 0; // initialize the count
payratetotal = hourstotal = grosstotal = taxtotal = nettotal = 0;
printf(REPORTHEADINGS);
fprintf(reportFile,REPORTHEADINGS);
fprintf(reportFile,REPORTHEADINGS2);
fprintf(reportFile,REPORTLINE);
do
{
printf(" Enter the last name ==> ");
scanf("%s",lastName);
printf(" Enter the first name ==> ");
scanf("%s",firstName);
printf("Enter hourly pay rate ");
scanf("%f",addr(payrate));
printf("Enter hours worked this pay period");
scanf("%f",addr(hours));

/* processing */
if (hours <= 40)
gross = hours * payrate;
else
gross = 40 * payrate + OVERTIMERATE * payrate * (hours-40);
tax = gross * TAXRATE;
net = gross - tax;

payratetotal = payratetotal + payrate;
hourstotal = hourstotal + hours;
grosstotal = grosstotal + gross;
taxtotal = taxtotal + tax;
nettotal = nettotal + net;


strcpy(fullName,lastName); // combine last + first names into full name
strcat(fullName,", ");
strcat(fullName,firstName);

//printf(format,fullName,payrate,hours,gross,tax,net); /* output */
printf(format,fullName,payrate,hours,gross,tax,net);
fprintf(reportFile,format,fullName,payrate,hours,gross,tax,net); /* output */
empCounter = empCounter + 1;
printf(" Do you have another employee(Y/N) ");
fflush(stdin); // clear the input buffer FIRST !!!!!!!!!!
scanf("%c",addr(answer));
} while (answer == 'Y' || answer == 'y');

printf(" You processed %2d employeesn",empCounter);
fprintf(reportFile,BLANKSPACE);
printf(format,"Totals",payratetotal,hourstotal,grosstotal,taxtotal,nettotal);
fprintf(reportFile,format,"Totals",payratetotal,hourstotal,grosstotal,taxtotal,nettotal); printf(format,"Averages",payratetotal/empCounter,hourstotal/empCounter,grosstotal/empCounter,taxtotal/empCounter,nettotal/empCounter);
fprintf(reportFile,format,"Averages",payratetotal/empCounter,hourstotal/empCounter,grosstotal/empCounter,taxtotal/empCounter,nettotal/empCounter);
fclose(reportFile);
fflush(stdin);
getchar();
return 0; // successful "Run" / complete, without Fault
}






Example
+ Show Spoiler +

and it should be changed like this.. in this order
3.0 Assign 3 - Payroll Version 3
3.1 getEmployeeData(out lastname,firstName as string,
out hours, payrate as real)
3.2 CalcGross(in hours, payrate as real, out grossPay as real)
3.3 CalcTax(in grossPay as real,
in TAXRATE as const real = 15%,
out taxdue as real)
3.4 CalcNet(in grossPay,taxdue as real, out netPay as real)
3.5 printDetailReportLine(in lastname,firstName as string,
in hours, payrate,grossPay,taxdue,
netPay as real)
3.6 printSummaryReport(in totHours, totPayrate,totGrossPay, totTaxdue,
totNetPay as real,
in empCounter as integer)



#include <stdio.h>
#define REPORTFORMATLINE " %3d + %3d = %4d\n"
void getTwoValues(int * a,int * b); // 3.1
int calcTheSum(int a, int b); // 3.2
void showReport(int a,int b,int sum); // 3.3

int main(void)
{
int a,b, sum;


getTwoValues(&a,&b); // call 3.1
sum = calcTheSum(a,b); // call 3.2
showReport(a,b,sum); // call 3.3
fflush(stdin);
getchar();
return 0;
}
void getTwoValues(int * a,int * b) // 3.1
{
printf(" Enter the value for a ==> ");
scanf("%d",a);
printf(" Enter the value for b ==> ");
scanf("%d",b);
}
int calcTheSum(int a, int b) // 3.2
{
return a + b;
}
void showReport(int a,int b,int sum)
{
printf(REPORTFORMATLINE, a,b,sum);
printf(" Press any key to end ....\n");
}






I still don't know what is the correct function for each module.. void, float, int and etc.. and sometimes it is mixed with other variables such as string, character and float.
Can anyone explain me about this? It would be nicer if you can show me an example.. Thank you!!


**
Life is not easy, sometimes you need to realize you gotta pack your bags and go back to the real world before you're old and broke with no education.
Koromon
Profile Joined May 2012
United States304 Posts
Last Edited: 2015-03-17 04:14:57
March 17 2015 04:03 GMT
#2
Maybe someone else can give you more helpful advice.. but it's easier to help if we know exactly what the error is. You're using something to compile it... what exactly are the errors?

As for understanding how functions are set up.. hope the following helps?

+ Show Spoiler +
<Return Type> functionName( arguments ) {
/* function */
}
where arguments usually are in the form of <type> <identifier>

So for instance (this is probably not going to be a very spectacular example), if you have a function

void printHelloWorld() {
printf("hello world\n");
}

You would call it in your main function simply by:
printHelloWorld();
Note this function has no arguments and the return type is void, meaning nothing is returned.

If you instead had a function like

int addNums( int a, int b ) {
return a + b;
}

then you would most likely call this function in main like so...
int someNumber = 5;
int anotherNumber = 7;
int poop = addNums(someNumber, anotherNumber);

Calling the function 'addNums' would RETURN an INT into the left side of the equal sign.
So yea.. poop would now equal 12.

Of course you could just simply call the function by
addNums(someNumber, anotherNumber)

But inside your main, there would be nothing that stored that sum, because even though the function tries to return a value, there is nothing in your main that is set to store that value.

But going back to the function
int addNums(int a, int b) {
...
}

The argument 1 in this case is an integer which will be referred to as 'a' in the function and argument 2 is also an integer but is referred to as 'b' inside the function. If you call addNums( 13, 7), inside addNums, you could reference 13 using a, and 7 using b. If you try say addNums( "hello", "rain");... well, I don't know exactly what will happen other than errors.





"Separating into multiple functions"

+ Show Spoiler +
From what I understood... that looks like it would mean you would want to
(1). Use a function to read in lastName/firstName, and payRate/hours
(2). condense updating all the 'total's (payratetotal, hourstotal... etc) in a function?

Given that... a function version of (1) would look something like the 'getTwoValues' function in your example.
And for (2), something like 'calcTheSum' would do.



Also 'final' edit: Hope you like programming! Googling your question and adding a stack overflow might be helpful. Stack overflow is almost like the TL of programming.

Another 'final' edit: TL has a programming thread too
http://www.teamliquid.net/forum/general/134491-the-big-programming-thread
Rain
Profile Blog Joined July 2011
120 Posts
March 17 2015 04:49 GMT
#3
Thanks for your answer Koromon!!.
So return value means output of the function?

for example
3.1 getEmployeeData(out lastname,firstName as string, out hours, payrate as real)

My first module has 2 string outputs and 2 float outputs.. and I wasn't sure so I tried with float function.

float getEmployeeData(float * hours, float * payrate); // 3.1

float getEmployeeData(float * hours, float * payrate)

{ printf(" Enter the last name ==> ");
scanf("%s",lastName);
printf(" Enter the first name ==> ");
scanf("%s",firstName);
printf("Enter hourly pay rate ");
scanf("%f",addr(payrate));
printf("Enter hours worked this pay period");
scanf("%f",addr(hours));
}

I compiled and these are the errors I got.
in function `float getEmployeeData{float, float}':
lastName undeclared
firstName undeclared

Life is not easy, sometimes you need to realize you gotta pack your bags and go back to the real world before you're old and broke with no education.
Bobbias
Profile Blog Joined March 2008
Canada1373 Posts
March 17 2015 05:42 GMT
#4
Yes, return value is the output from the function.

The 'undeclared' error means you never created something called lastName or firstName before you trued to use them.

Before you can use scanf to get the name, you need to create the variable to store the result, so you need to add:

string lastName;
string firstName;

At the beginning of the function. A function can't access variables you made outside the function, only whatever the input to the function is, and whatever variables you create inside the function itself.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
March 17 2015 05:49 GMT
#5
discuss it here: http://www.teamliquid.net/forum/general/134491-the-big-programming-thread
When you want something, all the universe conspires in helping you to achieve it.
Koromon
Profile Joined May 2012
United States304 Posts
Last Edited: 2015-03-17 05:56:34
March 17 2015 05:51 GMT
#6
Okay, to solve your problem, we'll follow exactly what the errors are.
+ Show Spoiler +

"in function 'float getEmployeeData{fload, float}'
-first, yes, return value is the output of the function. It will be very important in other functions, but you can do this one without a return type. I'll get to that later

'lastName undeclared'
'firstName undeclared'
So... we look at where 'lastName' and 'firstName' are used to see why the compiler is complaining. That would be in your scanf statements, where I assume you're trying to save what the user enters into 'lastName' and 'firstName'. So what is this 'undeclared' business about?

In C++ (and other languages), you have to 'declare' a variable before using it. However, when you declare a variable, it's only declared in the scope for which you declared it in. Which is to say, 'lastName' and 'firstName' have to be declared inside your function getEmployeeData (or globally) for you to use it in getEmployeeData. Even if you declare 'lastName' and 'firstName' inside main, that doesn't help getEmployeeData.

That's why there are no problems with 'payrate' and 'hours'. Arguments are in the form of <type> <identifier>, <type> <identifier>,... etc. <type> is like string/char/int/etc, <identifier> is just the name. In your case of getEmployeeData, you have two arguments:
1). type float*, identifier: hours
2). type float*, identifier: payrate
Arguments are sort of like free declarations. Regardless of what the name of the variable you pass into getEmployeeData, once you're inside getEmployeeData, the names of those two variables are treated as 'hours' and 'payrate'. But once you leave the function, those variables disappear.

But you don't want the variables to disappear right? After you call these functions, you want to have a last name inside 'lastName', and first name inside 'firstName', and so on. You might think that you'd be forced to output them 1 at a time as the return value but fear not! C++ isn't that dumb.

This, amongst other things is what pointers are for. I don't know if you've learned them, but in your code and in the example code pointers are being used. The '*' after a type generally means a pointer (maybe someone can correct me on this).

Which is to say, in your getEmployeeData, you actually have arguments that are pointers to floats. As to what this exactly means... I can't explain in very well D:
What I can guarantee, is that so long as you set up/call your function as the example getTwoValues does, even after exiting the function the scanned in values will reside inside the variables you want.


So yea... in summary, you need to declare lastName/firstName (duh), and you would do so in the same way that have you declared hours and payrate inside the function.

Edit:
+ Show Spoiler +
I read your file again, and I noticed that at the top there was this stuff:
Data Design Scheme
Declare lastName,firstName, fullName as string
Declare payrate,hours,gros,tax,net as real
Declare answer as character
Declare empCounter as integer
Declare reportFile as file
*/

I assume that's what your assignment file started with. This is what I meant earlier about declaring things globally. If you delcared your variables here as opposed to inside main, the compiler probably also wouldn't complain.



Rain
Profile Blog Joined July 2011
120 Posts
March 17 2015 07:31 GMT
#7
Thanks to people who answered my questions! I'm currently facing another problem. I have to printout a report that contains strings and numbers

printf(format,fullName,payrate,hours,gross,tax,net); fullName is a string and others are floats. They are different variables.. How can I put these together in the same function?


I tried in this way, but compiler tells me
in function `int main[]':
cannot convert`const char*`to `float' for argument `1' to `void printDetailReportLine(float,float,float,float,float)'


Code Below
+ Show Spoiler +

void printDetailReportLine(float hours, float payrate, float gross, float tax, float net); // 3.5


printDetailReportLine(format,fullName,payrate,hours,gross,tax,net); // Call module 3.5





void printDetailReportLine(float hours, float payrate, float gross, float tax, float net) // 3.5
{

char lastName[15+1]; // max length is 15 characters
char firstName[10+1]; // max length is 10 characters
char fullName[15+10+2+1];


int empCounter;
FILE * reportFile; // read "reportFile is a pointer to a file "
strcpy(fullName,lastName); // combine last + first names into full name
strcat(fullName,", ");
strcat(fullName,firstName);

//printf(format,fullName,payrate,hours,gross,tax,net); /* output */
printf(format,fullName,payrate,hours,gross,tax,net);
fprintf(reportFile,format,fullName,payrate,hours,gross,tax,net); /* output */
empCounter = empCounter + 1;
}
Life is not easy, sometimes you need to realize you gotta pack your bags and go back to the real world before you're old and broke with no education.
Cascade
Profile Blog Joined March 2006
Australia5405 Posts
March 17 2015 07:34 GMT
#8
On March 17 2015 14:51 Koromon wrote:
Okay, to solve your problem, we'll follow exactly what the errors are.
+ Show Spoiler +

"in function 'float getEmployeeData{fload, float}'
-first, yes, return value is the output of the function. It will be very important in other functions, but you can do this one without a return type. I'll get to that later

'lastName undeclared'
'firstName undeclared'
So... we look at where 'lastName' and 'firstName' are used to see why the compiler is complaining. That would be in your scanf statements, where I assume you're trying to save what the user enters into 'lastName' and 'firstName'. So what is this 'undeclared' business about?

In C++ (and other languages), you have to 'declare' a variable before using it. However, when you declare a variable, it's only declared in the scope for which you declared it in. Which is to say, 'lastName' and 'firstName' have to be declared inside your function getEmployeeData (or globally) for you to use it in getEmployeeData. Even if you declare 'lastName' and 'firstName' inside main, that doesn't help getEmployeeData.

That's why there are no problems with 'payrate' and 'hours'. Arguments are in the form of <type> <identifier>, <type> <identifier>,... etc. <type> is like string/char/int/etc, <identifier> is just the name. In your case of getEmployeeData, you have two arguments:
1). type float*, identifier: hours
2). type float*, identifier: payrate
Arguments are sort of like free declarations. Regardless of what the name of the variable you pass into getEmployeeData, once you're inside getEmployeeData, the names of those two variables are treated as 'hours' and 'payrate'. But once you leave the function, those variables disappear.

But you don't want the variables to disappear right? After you call these functions, you want to have a last name inside 'lastName', and first name inside 'firstName', and so on. You might think that you'd be forced to output them 1 at a time as the return value but fear not! C++ isn't that dumb.

This, amongst other things is what pointers are for. I don't know if you've learned them, but in your code and in the example code pointers are being used. The '*' after a type generally means a pointer (maybe someone can correct me on this).

Which is to say, in your getEmployeeData, you actually have arguments that are pointers to floats. As to what this exactly means... I can't explain in very well D:
What I can guarantee, is that so long as you set up/call your function as the example getTwoValues does, even after exiting the function the scanned in values will reside inside the variables you want.


So yea... in summary, you need to declare lastName/firstName (duh), and you would do so in the same way that have you declared hours and payrate inside the function.

Edit:
+ Show Spoiler +
I read your file again, and I noticed that at the top there was this stuff:
Data Design Scheme
Declare lastName,firstName, fullName as string
Declare payrate,hours,gros,tax,net as real
Declare answer as character
Declare empCounter as integer
Declare reportFile as file
*/

I assume that's what your assignment file started with. This is what I meant earlier about declaring things globally. If you delcared your variables here as opposed to inside main, the compiler probably also wouldn't complain.




Just want to add that it is in general not a good idea to use global variables for things like this. The variables you use in this function are just used to pass the input from the user to the output of the "getEmployeeData" function, and isn't interesting otherwise. So the proper way to do it is to declare it inside the function.
zamzx
Profile Joined March 2014
United States7 Posts
Last Edited: 2015-03-17 08:49:54
March 17 2015 08:46 GMT
#9
Strings are simply arrays (containers) of letters or numbers and therefore any variable can be printed as a string.

In C++ for the printf you need to specify where the variable is going and which type it is. This site goes over the different identifiers you can put inside of printf as well as a few examples CLICKY FOR LINKY.

But I think this one has a code snippet that clearly illustrates your problem: http://gillius.org/ctut/part1.htm

printf("The value of x is: %i and the value of y is: %i", x, y);

In that line, the String is everything inside of the "" and the %i tells the complier where a data type is going to go. The x and y following that are the variables that the printf command will read and place in the respective %i's. (But it will be converting the int-type into the String type, so the command can print a String)

So basically, when you're printing something you need to specify what type of data each variable is so it can properly convert it and, well, f'in print it.


I am long past innocence, and fast approaching apathy
Gowerly
Profile Blog Joined July 2011
United Kingdom916 Posts
March 17 2015 17:11 GMT
#10
Part of the problem is this:


void printDetailReportLine(float hours, float payrate, float gross, float tax, float net); // 3.5


printDetailReportLine(format,fullName,payrate,hours,gross,tax,net); // Call module 3.5


You're calling printDetailReportLine with things that aren't what the function is expecting, or in the right order!

In general, programming languages are dumb, they don't know what you mean, only what you tell them.

So you can call:

printDetailReportLine(hours, payrate, gross ,tax, net); // Call module 3.5

but "format" and "fullName" can't go into that function, as the function does not expect it.

If you need it to expect those variables, then you will need to add them to the function definition and implementation.
I will reduce you to a series of numbers.
codonbyte
Profile Blog Joined June 2011
United States840 Posts
March 18 2015 20:56 GMT
#11
Oh god, that code needs to be refactored sooo badly. If I were you, before even getting started with the problem, I would do some major refactoring on that code.

For starters, I see you have some macros defined. Macros are evil. Consider replacing them with inline functions if possible.

Now, about your use of #define:
#define REPORTHEADINGS " Employee Pay Hours Gross Tax Netn"
#define REPORTHEADINGS2 " Name Rate Worked Pay Amount Payn"
#define REPORTLINE " ======== ==== ====== ===== ====== ======/n"
#define format " %-23s%8.2f%10.2f%10.2f%8.2f%10.2fn"
#define TAXRATE 0.15
#define OVERTIMERATE 1.5
#define BLANKSPACE " /n"

Here, you are simply using #define to define a symbolic constant. Don't do that. If you need to define a symbolic constant, use the const keyword instead. For example:

const float OVERTIMERATE = 1.5;
const float TAXRATE = .15;
etc..

Why is it better to use const instead of #define? There are several advantages:
First of all, #define macros are globally visible throughout your entire program. Not even namespaces constrain them. This means that if you use #define macros, you risk running into name-clashes the larger your program gets. Think about it: in a large program you are going to be using loads of files that were written by other people. How do you know none of them used "TAXRATE" or "OVERTIMERATE" in part of their code?

Before the compiler even gets to see your code, the preprocessor runs and performs simple text-replacements wherever it encounters a #define macro. This can alter your code in ways you wouldn't expect. Go type "C++ macros evil" into google and read all the horror stories about the hundreds of thousands of hours that are wasted by evil loathsome macros. You'll read countless tails of bugs that occured because the user's code was silently altered by a define macro in a different file in a different namespace that they didn't even write.

That, my friend is the antithesis of encapsulation, and therefore it is the antithesis of good OOP, which is what C++ is supposed to be about.

To be honest, the code you listed looks a lot more like C than C++. I'd change that before even starting on the program. You'll save yourself a headache in the shortrun, and you'll learn good habits that will save your ass in the long run. Please man, take it from me.

I taught myself C++ in high-school, but I didn't bother to use good coding practices. I was passionate about coding; all I wanted to do was create my own game. Well, I did eventually create my own game, but it absolutely sucked. Thing had so many goddamn memory leaks that most antivirus programs would instantly gobble it up, thinking it was a virus. And I wasted SO many hours debugging hard-to-find logic errors, dangling pointers, overstepped array bounds, you name it.
Procrastination is the enemy
Ilikestarcraft
Profile Blog Joined November 2004
Korea (South)17727 Posts
March 19 2015 02:23 GMT
#12
On March 19 2015 05:56 codonbyte wrote:
Thing had so many goddamn memory leaks that most antivirus programs would instantly gobble it up, thinking it was a virus.

I don't know why this made me laugh so much.
"Nana is a goddess. Or at very least, Nana is my goddess." - KazeHydra
Dumbledore
Profile Joined April 2011
Sweden725 Posts
March 19 2015 06:38 GMT
#13
Hi Rain, do you happen to have skype? I would love to help you with your C++ assignments :D
Have a nice day ;)
Dumbledore
Profile Joined April 2011
Sweden725 Posts
March 19 2015 06:58 GMT
#14
Been looking at the code, and a lot of the code is written in C style instead of C++.

(Tips below are not about Object Orientation)
In C, you had to put void as the argument to functions with no parameters, for example:
"int main(void)", however in C++ this is not necessary so just having "int main()" is cleaner.

Not sure if you know this or not but you have written:
"[15+1]; // max length is 15 characters", that would actually be a max length of 16 characters, but the range would go from 0 to 15, making it 16 because of that it starts at 0.

Instead of empCounter = empCounter + 1; you can simply write ++empCounter; or empCounter++;

"I still don't know what is the correct function for each module.. void, float, int and etc.. and sometimes it is mixed with other variables such as string, character and float.
Can anyone explain me about this? It would be nicer if you can show me an example.. Thank you!!"

C++ has some primitive datatypes.
Some of them are: int, float, double, char, etc.
I've written a short article here explaining different variable types: http://discovercpp.com/3-variables-and-their-uses/
But basically an int is an integer, it cant have decimal points, a double is a "double precision" decimal variable, meaning that it can hold more decimals than a float can, but its also twice as large in memory. char is a single character usually, sometimes called "byte" by others. A string is what is called an "array" of chars.

When you declare a function such as this:
int returnSum(int a, int b)
{
return a + b;
}

The int at the start in "int returnSum" tells the computer that this is going to be a function that will return an int variable.
Then in the brackets we say what arguments we expect, in this case its 2 integers, one that will be named a and one named b inside the function. Then we simply return the sum. Since both of the variables are integers, a + b will be an integer.

You use a lot of DEFINE statements for constants, in C++ it's not "good practise". Use the const keyword and a normal variable inside of the main.

"int main(void) // main function HEADER
{

char lastName[15+1]; // max length is 15 characters
char firstName[10+1]; // max length is 10 characters
char fullName[15+10+2+1];"

would become:

"int main(void) // main function HEADER
{
const float TAXRATE = 0.15; // The const word makes the value unchangeable.
... // etc.
char lastName[15+1]; // max length is 15 characters
char firstName[10+1]; // max length is 10 characters
char fullName[15+10+2+1];"

Then we have some pointer usage
void getTwoValues(int * a,int * b) // 3.1

Dont know if you know this, the stars (*) makes it a pointer variable. I recently wrote a small article on that aswell :D
http://discovercpp.com/4-pointers-a-step-into-the-unknown/
Have a nice day ;)
madnessman
Profile Blog Joined May 2009
United States1581 Posts
March 19 2015 08:59 GMT
#15
As others have said, programming related questions should go to the programming threadprogramming thread.

That said, have you considered using structs to represent employees instead of having a bunch of loose variables in the main function? I'd say that a class would be ideal since you're learning OOP and C++ but I'm assuming that you haven't gotten to classes yet. You seem somewhat with familiar C (since your code reads like C code) so you should be familiar with structs right?

Anyway, I decided to just rewrite your program since there were so many issues with it (no offense). My code definitely isn't perfect. It's pretty inefficient, I didn't bother trying to format my output nicely, and I didn't set any max lengths for my strings. I also used a std::vector which you might not be allowed to use in your assignment if you haven't covered vectors in class yet. I'm sure some people here are going to find other errors or problems with my style but I hope my code can be a good starting point or reference for your own solution to the assignment.

+ Show Spoiler +
#include <iostream> // cout, cin, string
#include <vector> // vector<employee>

using namespace std;

struct employee
{
// name
string first, last;
// pay info
double hours, payRate;
};

// function declarations
employee getEmployeeData();
double calcGross(employee, double);
double calcTax(employee, double, double);
double calcNet(employee, double, double);
void printDetailReport(employee, double, double);
void printSummaryReport(vector<employee>, double, double);

int main()
{
// variable declaration
vector<employee> allEmployees;
char loopInput('Y');
const double OVERTIMERATE(1.5), TAXRATE(0.15);
// getting all employee info
while (loopInput=='Y')
{
employee temp;
temp = getEmployeeData();
printDetailReport(temp, TAXRATE, OVERTIMERATE);
allEmployees.push_back(temp);

// input for loop
cout << "Do you have another employee (Y/N): ";
cin >> loopInput;
// basic error handling
if (loopInput!='Y' && loopInput!='N')
{
cout << "Invalid input. Please enter \"Y\" or \"N\": ";
cin >> loopInput;
}
}
printSummaryReport(allEmployees, TAXRATE, OVERTIMERATE);
}

// function definitions
employee getEmployeeData()
{
employee ans;
cout << "Enter name (first last): ";
cin >> ans.first >> ans.last;
cout << "Enter hours worked: ";
cin >> ans.hours;
cout << "Enter pay rate: ";
cin >> ans.payRate;
return ans;
}

double calcGross(employee person, double overtime)
{
double grosspay;
if (person.hours<=40)
grosspay = person.hours*person.payRate;
else
grosspay = 40*person.payRate + overtime*person.payRate*(person.hours-40);
return grosspay;
}

double calcTax(employee person, double taxrate, double overtime)
{
return calcGross(person, overtime) * taxrate;
}

double calcNet(employee person, double taxrate, double overtime)
{
return calcGross(person, overtime) - calcTax(person, taxrate, overtime);
}

void printDetailReport(employee person, double taxrate, double overtime)
{
cout << "Name: " << person.first << " " << person.last << endl;
cout << "Pay hours: " << person.hours << endl;
cout << "Pay rate: " << person.payRate << endl;
cout << "Gross: " << calcGross(person, overtime) << endl;
cout << "Tax: " << calcTax(person, taxrate, overtime) << endl;
cout << "Net: " << calcNet(person, taxrate, overtime) << endl;
}

void printSummaryReport(vector<employee> allEmployees, double taxrate, double overtime)
{
double hours, gross, tax, net;
hours = gross = tax = net = 0;
for (size_t i = 0; i < allEmployees.size(); ++i)
{
hours += allEmployees[i].hours;
gross += calcGross(allEmployees[i], overtime);
tax += calcTax(allEmployees[i], taxrate, overtime);
net += calcNet(allEmployees[i], taxrate, overtime);
}
cout << "# of employees: " << allEmployees.size() << endl;
cout << "Total hours: " << hours << endl;
cout << "Total gross: " << gross << endl;
cout << "Total tax: " << tax << endl;
cout << "Total net: " << net << endl;
}
Gamegene
Profile Blog Joined June 2011
United States8308 Posts
March 19 2015 09:56 GMT
#16
hey he gets to bypass the homework rules! guess there's some perks to being an ex korean pro gamer
Throw on your favorite jacket and you're good to roll. Stroll through the trees and let your miseries go.
codonbyte
Profile Blog Joined June 2011
United States840 Posts
March 19 2015 17:31 GMT
#17
On March 19 2015 18:56 Gamegene wrote:
hey he gets to bypass the homework rules! guess there's some perks to being an ex korean pro gamer

Thing is, this is a blog. Teamliquid.net tends to be much more lenient about what's allowed in blogs.
Procrastination is the enemy
Aerisky
Profile Blog Joined May 2012
United States12129 Posts
March 19 2015 20:07 GMT
#18
Blogs have been closed for homework help in the past. They're where most homework help posts have been made anyway.
Jim while Johnny had had had had had had had; had had had had the better effect on the teacher.
Cascade
Profile Blog Joined March 2006
Australia5405 Posts
March 19 2015 21:32 GMT
#19
Ex Korean pros definitely get to do at least a few homework blogs before anyone should complain IMO.
Please log in or register to reply.
Live Events Refresh
Next event in 4h 11m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
WinterStarcraft629
Nina 175
NeuroSwarm 121
ProTech74
StarCraft: Brood War
sSak 222
Bale 64
Movie 13
Shine 12
Icarus 10
yabsab 9
Dota 2
LuMiX1
League of Legends
JimRising 723
Counter-Strike
Stewie2K888
semphis_49
Super Smash Bros
Mew2King82
Other Games
summit1g7661
shahzam786
C9.Mang0342
Maynarde130
ViBE2
Organizations
Other Games
gamesdonequick1175
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 12 non-featured ]
StarCraft 2
• practicex 24
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Rush1929
Upcoming Events
Sparkling Tuna Cup
4h 11m
Afreeca Starleague
4h 11m
Soulkey vs Barracks
EffOrt vs Rush
Monday Night Weeklies
10h 11m
Afreeca Starleague
1d 4h
BeSt vs Alone
Queen vs Bisu
The PondCast
3 days
RSL Revival
3 days
Cure vs SHIN
Reynor vs Zoun
RSL Revival
4 days
Classic vs TriGGeR
ByuN vs Maru
Online Event
4 days
BSL Team Wars
4 days
Team Bonyth vs Team Dewalt
BSL Team Wars
4 days
[ Show More ]
RSL Revival
5 days
Maestros of the Game
5 days
Cosmonarchy
5 days
Bonyth vs Dewalt
[BSL 2025] Weekly
5 days
RSL Revival
6 days
Maestros of the Game
6 days
BSL Team Wars
6 days
Liquipedia Results

Completed

Copa Latinoamericana 4
SEL Season 2 Championship
HCC Europe

Ongoing

BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21: BSL Points
ASL Season 20
CSL 2025 AUTUMN (S18)
LASL Season 20
RSL Revival: Season 2
Maestros of the Game
Chzzk MurlocKing SC1 vs SC2 Cup #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1

Upcoming

2025 Chongqing Offline CUP
BSL Polish World Championship 2025
BSL Season 21
BSL 21 Team A
EC S1
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
MESA Nomadic Masters Fall
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.