r/CPPtogether • • Feb 11 '20

Assignment 2

Write a program that asks the user to input an employees name, then separately, hours worked. The program should multiply the hours worked by a pay rate of $18.50. The user would like the program to return the name and hours entered, the pay rate, and the total net pay for the employee, on separate lines. Ultimately, the program should output:

Employee name: (nameInput)
Hours worked: (hoursInput)
Pay rate: 18.50
Net pay: (product of hoursInput and pay rate)
3 Upvotes

9 comments sorted by

View all comments

Show parent comment

3

u/Mninek Feb 11 '20

Why not initialize double netPay after you get a value for hoursWorked? After that just output everything as normal. Also any particular reason why you don't just initialize like double payRate = 18.50? I know they are both the same but the way you did seems like it might get confusing if youre just starting out. Not sure if one is better than the other though.

1

u/trooflaw Feb 11 '20

so my current issue, is if you run that code as is, the output for employeeName is only one word. for instance, if I input Jeff Bridges as employeeName it outputs

how many hours did Jeff work?

rather than

how many hours did Jeff Bridges work?

also, after this, it asks for the input for hoursWorked, as it should, however does not allow user input

1

u/Mninek Feb 11 '20

So the way cin works (99% sure this will be the correct explanation lol) is it reads the input bar until I gets to a white space character. For example, it could be a new line (which in c++ is \n). This is also true for spaces. So cin is reading the name up until the space character, then it stops. Next, it asks for hoursWorked, and checks the input bar BUT your bar isn't fully empty, once it previously read "Jeff Bridges". So the cin for hoursWorked will read "Bridges".

The way to get around this is to use getline and ignore functions. There should be a ton of resources online about the implementation of these functions.

1

u/flappyprince Feb 12 '20

For local variables they are essentially the same, but brace initialization has better performance on some other data types, so it's favorable for consistency reasons. Another advantage over copy initialization, is that you'll get an error if you try to initialize a value which the type cannot hold. For example:

Int x {9.01}; // This would produce an error