• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

C++ programming

Joined
Dec 2, 2009
Messages
3,351 (0.64/day)
System Name Dark Stealth
Processor Ryzen 5 5600x
Motherboard Gigabyte B450M Gaming rev 1.0
Cooling Snowman, arctic p12 x2 fans
Memory 16x2 DDR4 Corsair Dominator Pro
Video Card(s) 3080 10gb
Storage 2TB NVME PCIE 4.0 Crucial P3 Plus, 1TB Crucial MX500 SSD, 4TB WD RED HDD
Display(s) HP Omen 34c (34" monitor 3440x1440 165Hz VA panel)
Case Zalman S2
Power Supply Corsair 750TX
Mouse Logitech pro superlight, mx mouse s3, Razer Basiliskx with battery
Keyboard Custom mechanical keyboard tm680
Software Windows 11
Benchmark Scores 70-80 fps 3440x1440 on cyberpunk 2077 max settings
I am trying to make a game and was putting in the speed of the enemies and the hero
It is text based so nothing to think of except plain C++
But i came through something tricky which i thought it could be implemented in another way
If i type it like this:
Code:
if (enemy.speed() >= player.speed()){
player.life = player.life - enemy.attack;
if(player.life <= 0)
{
cout << "game over";
}
enemy.life = enemy.life - player.attack;
And the code gets kinda disgusting. Is there some other way to make this?
I think i found it somewhere but can't remember
 
Last edited:

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.21/day)
Location
Cheeseland (Wisconsin, USA)
I completely missed this thread when I was in the hospital, Alek.
Are you still working on trying to make this cleaner or looking for an alternate way of doing it?
 

xbonez

New Member
Joined
Nov 29, 2010
Messages
1,182 (0.24/day)
Location
Philly, PA (US)
System Name Winter
Processor AMD Phenom II x4 965 BE @ 4.0Ghz
Motherboard MSI 790FX-GD70
Cooling Corsair H50 Liquid Cooling
Memory 2 x 2Gb Gskill Ripjaws 1600Mhz (7-7-7-24@1.6V)
Video Card(s) Asus GTX 470 @ Stock (Zalman VF3000 cooler)
Storage 2 x Samsung Spinpoint F3 500GB (RAID 0)
Display(s) Hanns G 28" @ 1920x1200
Case Antec 1200
Audio Device(s) Onboard -- TosLink --> Z5500
Power Supply Corsair 850TX 850W PSU
Software Win 7 64-bit Ultimate
Given the code you have posted above, there isn't a great deal of refactoring that can be done, however, you should try designing something like this.

At the moment, 'speed' seems to be a method, while 'attack' is a property. I think you'd be better off having speed as a property (since it really is just a property of the character), while attack should be a method.

The attack method should take care of reducing the life of the subject getting attacked. Also, setup an event that get's raised when life becomes 0 or less. The event handler should be responsible of cleaning up code and ending the game if the owner object is the player.

This way, you don't need to replicate the code above everytime. You just need to worry about calling attack() which will take care of everything else.

Finally, you enemy and player classes should derive from a possible abstract class such as 'character' which has the properties life, speed etc., as well as methods such as attack(), defend() etc. These method definitions can be overridden. This will make it easier for you expand the game, if you want to add different kind of enemies etc.
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
I have question. Im doing some home work and I am stuck on something really simple!

How do you put a space between the inputs and outputs? I can write the code but when I run the program everything is line by line but I was to say but a space between my inputs and outputs. Also I want to put a space on the output cout << "Employee: " << first << last << endl

Here is my whole code. This is suppose to be a program to help output monthly paycheck for an employee

Code:
#include <iostream>	
#include <iomanip>

using namespace std;

int main(void)
{
	char	first [20], 
		last [20];
	double 	monpay;					

	
	cout << "Employee First Name: " << endl;	        
	cin >> first;
	cout << "Employee Last Name: " << endl;	        
	cin >> last;
	cout << "Monthly Pay: " << endl;
	cin >> monpay;

	
	double	fed, state, ssmed;                                         

	fed = monpay * 0.15;
	state = monpay * 0.035;
	ssmed = monpay * 0.085;
	
	
	cout	<< "Employee: " << first << last << endl	
		<< "Gross Amount: " << fixed << setprecision(2) << setw(15) << setfill('.') << monpay << "$" << endl	
		<< "Federal Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << fed << "$" << endl
		<< "State Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << state << "$" << endl
		<< "Social Security and Medicare Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << ssmed << "$" << endl
		<< "Health Insurance: " << fixed << setprecision(2) << setw(15) << setfill('.') << "75$" << endl
		<< "Net Pay: " << fixed << setprecision(2) << setw(15) << setfill('.') << monpay - fed - state - ssmed - 75 << "$" << endl;

	
cout	<< "Press any key to exit." << endl;
	cin.ignore(2);
   
	return 0;				
}
 
Joined
Nov 22, 2007
Messages
1,398 (0.23/day)
Location
Hyderabad,India
System Name MSI apache ge62 2qd
Processor intel i7 5700HQ
Memory 12 Gb
Video Card(s) GTX960m
Storage 1TB
Display(s) Dell 24'
You need to remove the endl statement at those few cout statements. (/n can also be used for new line, so /n before the next statement puts a new line.)

Code:
#include <iostream>	
#include <iomanip>

using namespace std;

int main(void)
{
	char	first [20], 
		last [20];
	double 	monpay;					

	
	cout << "Employee First Name: "  ;	        
	cin >> first;
	cout << "\nEmployee Last Name: "  ;	        
	cin >> last;
	cout << "\nMonthly Pay: " ;
	cin >> monpay;

	
	double	fed, state, ssmed;                                         

	fed = monpay * 0.15;
	state = monpay * 0.035;
	ssmed = monpay * 0.085;
	
	
	cout	<< "\nEmployee: " << first << last << endl	
		<< "Gross Amount: " << fixed << setprecision(2) << setw(15) << setfill('.') << monpay << "$" << endl	
		<< "Federal Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << fed << "$" << endl
		<< "State Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << state << "$" << endl
		<< "Social Security and Medicare Tax: " << fixed << setprecision(2) << setw(15) << setfill('.') << ssmed << "$" << endl
		<< "Health Insurance: " << fixed << setprecision(2) << setw(15) << setfill('.') << "75$" << endl
		<< "Net Pay: " << fixed << setprecision(2) << setw(15) << setfill('.') << monpay - fed - state - ssmed - 75 << "$" << endl;

	
cout	<< "Press any key to exit." << endl;
	cin.ignore(2);
   
	return 0;
    		
}
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
Would you know how to put a space between first and last name on the output side?

When I use the code

cout << "\nEmployee: " << first << last << endl

It outputs it to say "BrandonHarrison" < I want a space between my name you see?
 
Joined
Nov 22, 2007
Messages
1,398 (0.23/day)
Location
Hyderabad,India
System Name MSI apache ge62 2qd
Processor intel i7 5700HQ
Memory 12 Gb
Video Card(s) GTX960m
Storage 1TB
Display(s) Dell 24'
cout << "\nEmployee: " << first<<" " << last << endl
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
AHH! That worked like a charm. So input "" marks for spaces in output code.
 
Joined
Nov 22, 2007
Messages
1,398 (0.23/day)
Location
Hyderabad,India
System Name MSI apache ge62 2qd
Processor intel i7 5700HQ
Memory 12 Gb
Video Card(s) GTX960m
Storage 1TB
Display(s) Dell 24'
no, " " white space :D
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
no, " " white space :D

Ahh so "" with a space INSIDE the quotations is a white space? NICE! I am starting to LOVE this C++ if I continue to keep learning and I am so thankful you guys are helping me! I want to at least be able to pass this class and continue building small programs in my spare time.
 
Joined
Dec 2, 2009
Messages
3,351 (0.64/day)
System Name Dark Stealth
Processor Ryzen 5 5600x
Motherboard Gigabyte B450M Gaming rev 1.0
Cooling Snowman, arctic p12 x2 fans
Memory 16x2 DDR4 Corsair Dominator Pro
Video Card(s) 3080 10gb
Storage 2TB NVME PCIE 4.0 Crucial P3 Plus, 1TB Crucial MX500 SSD, 4TB WD RED HDD
Display(s) HP Omen 34c (34" monitor 3440x1440 165Hz VA panel)
Case Zalman S2
Power Supply Corsair 750TX
Mouse Logitech pro superlight, mx mouse s3, Razer Basiliskx with battery
Keyboard Custom mechanical keyboard tm680
Software Windows 11
Benchmark Scores 70-80 fps 3440x1440 on cyberpunk 2077 max settings
@brandon
Omg, i cannot believe you don't know the space!
Anyway, i was wondering for the second time what book you use
It is weird there is no spaces explanations, but there is a cin.ignore()
which i never heard of!
@xbonez
I think i nearly found it, but there wasn't much.
I make functions for each, but that is a bit weird
because i wanted to use the private and public
for them. I couldn't and i think i need to learn much more
But after all i don't profit anything with this stupid game
@kreij
I hope you are better kreij
Well, i never give up on something
Unless that something has given up already :)
It is not exactly finding an alternate
I just wanted to use the private and public
on the class enemy, but i wont dare to make it
right now. I am still in the middle of nowhere,
i want to
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
@brandon
Omg, i cannot believe you don't know the space!
Anyway, i was wondering for the second time what book you use
It is weird there is no spaces explanations, but there is a cin.ignore()
which i never heard of!

Im new alek, take it easy on me LOLZ I am also learning ALOT from your guys! I will keep posting more problems that the awesome TPU programming department can help solve

*EDIT*

Just got posed with this question

Suppose you are given the following variable declarations:

int x, y;
char ch;

What values (if any) are assigned to x, y, and ch after each of these statements execute?
Assume that the input to each statement is the same: 5 28 36

a. cin >> x >> y >> ch;
b. cin >> ch >> x >> y;
c. cin >> x >> ch >> y;
d. cin >> x >> y;
cin.get(ch);

explain to me what they are asking for here?
 
Joined
Aug 10, 2007
Messages
4,267 (0.70/day)
Location
Sanford, FL, USA
Processor Intel i5-6600
Motherboard ASRock H170M-ITX
Cooling Cooler Master Geminii S524
Memory G.Skill DDR4-2133 16GB (8GB x 2)
Video Card(s) Gigabyte R9-380X 4GB
Storage Samsung 950 EVO 250GB (mSATA)
Display(s) LG 29UM69G-B 2560x1080 IPS
Case Lian Li PC-Q25
Audio Device(s) Realtek ALC892
Power Supply Seasonic SS-460FL2
Mouse Logitech G700s
Keyboard Logitech G110
Software Windows 10 Pro
What values (if any) are assigned to x, y, and ch after each of these statements execute?
Assume that the input to each statement is the same: 5 28 36

a. cin >> x >> y >> ch;
b. cin >> ch >> x >> y;
c. cin >> x >> ch >> y;
d. cin >> x >> y;
cin.get(ch);

explain to me what they are asking for here?

The input is 5 space 28 space 36. Spaces, tabs, and newlines are valid separator characters when you want to provide multiple input.

After execution a, I believe you'll have x = 5, y = 28, and ch = 36 (as a string). Makes b and c easy to figure out. As for d, I have a couple guesses, but don't have enough experience with this language to know exactly how it will play out - will cin.get(ch) see " 36" or "36"? Is d even valid at all? Etc.

http://www.cplusplus.com/reference/iostream/istream/get/
http://www.minich.com/education/wyo/cplusplus/cplusplusch10/getfunction.htm#get
 
Last edited:

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
Problem of the week:

Write a program that generates all the factors of a number entered by the user. For instance, the number 12 has the factors 2 * 2 * 3.

Code:
#include<iostream>
using namespace std;
int factor(int& n)
{
for(int k=2; k<=n; k++)
if(n%k==0)
{
n = n/k;
return k;
}
}
int main()
{
int n;
int p=0;
do
{
cout << "Enter a Positive Integer :";
cin >> n;
}while(n<=0);
cout << "Factors are " << endl;
while(1)
{

if(n==1) break;
cout << factor(n) << " ";
p++;
if(p%4==0) cout << endl; // new line after every 4 factors !!
}
system("pause");
return 0;

}
 

xbonez

New Member
Joined
Nov 29, 2010
Messages
1,182 (0.24/day)
Location
Philly, PA (US)
System Name Winter
Processor AMD Phenom II x4 965 BE @ 4.0Ghz
Motherboard MSI 790FX-GD70
Cooling Corsair H50 Liquid Cooling
Memory 2 x 2Gb Gskill Ripjaws 1600Mhz (7-7-7-24@1.6V)
Video Card(s) Asus GTX 470 @ Stock (Zalman VF3000 cooler)
Storage 2 x Samsung Spinpoint F3 500GB (RAID 0)
Display(s) Hanns G 28" @ 1920x1200
Case Antec 1200
Audio Device(s) Onboard -- TosLink --> Z5500
Power Supply Corsair 850TX 850W PSU
Software Win 7 64-bit Ultimate
@brandonwh64:

Just a few comments on your code.

Avoid using commands like

Code:
system("pause");

They break the cross platform compatibility of your app.

And instead of doing

Code:
while(1)
{
if (n==1) break;

Why not just do

Code:
while (n != 1)
{
 
Joined
Dec 2, 2009
Messages
3,351 (0.64/day)
System Name Dark Stealth
Processor Ryzen 5 5600x
Motherboard Gigabyte B450M Gaming rev 1.0
Cooling Snowman, arctic p12 x2 fans
Memory 16x2 DDR4 Corsair Dominator Pro
Video Card(s) 3080 10gb
Storage 2TB NVME PCIE 4.0 Crucial P3 Plus, 1TB Crucial MX500 SSD, 4TB WD RED HDD
Display(s) HP Omen 34c (34" monitor 3440x1440 165Hz VA panel)
Case Zalman S2
Power Supply Corsair 750TX
Mouse Logitech pro superlight, mx mouse s3, Razer Basiliskx with battery
Keyboard Custom mechanical keyboard tm680
Software Windows 11
Benchmark Scores 70-80 fps 3440x1440 on cyberpunk 2077 max settings
An important note from other programmers to me was that system("pause")
is extremely worse. Instead use cin.get(); (it is 10 times faster)
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
An important note from other programmers to me was that system("pause")
is extremely worse. Instead use cin.get(); (it is 10 times faster)

Thank you! I will change my end line on my future programs. This week there is no programs I have to write due to midterms but There is a lab with pre written code if you guys want to take a look.
 
Joined
Sep 10, 2008
Messages
532 (0.09/day)
Location
VA/PA
System Name Freyja
Processor Core i7 3770K
Motherboard AsRock Z77 Extreme4
Cooling Cooler Master Hyper 212 EVO
Memory 16 GB GSkill Sniper
Video Card(s) Diamond Radeon HD 7970
Storage Kingston HyperX 240 GB SSD + Seagate 2 TB HD
Display(s) Dell U2410
Case NZXT Tempest 210
Audio Device(s) Asus Xonar Essence STX
Power Supply Seasonic X-Series 750W
Software Ubuntu 13.04 64 bit
Subbing because I may need to use this thread in the future, seeing as I'm currently in a C++ class right now :D.
 

brandonwh64

Addicted to Bacon and StarCrunches!!!
Joined
Sep 6, 2009
Messages
19,542 (3.67/day)
Subbing because I may need to use this thread in the future, seeing as I'm currently in a C++ class right now :D.

I am also doing C++ at the moment and from what these guys here on TPU have helped me with is phenomenal!

*EDIT*

This weeks questions.

To begin this exercise, create a VC++ project and copy the following code into your project. Make sure that the project compiles successfully

Code:
#include <iostream>

using namespace std;

int main()
{
	int input;
	int back1 = 1, back2 = 0;
	int current = 1;

	cout << "Enter which number in the Fibonacci number sequence you want to find." << endl;
	cout << "The first and second Fibonacci numbers are 1." << endl;
	cin >> input;

	while (input < 1)
	{
		cout << "You must enter a value greater than 0, try again." << endl;
		cin >> input;
	}

	if (input > 2)
	{
		for(int i = 2; i < input; i++)
		{
			back2 = back1;
			back1 = current;
			current = back1 + back2;
		}
	}

	cout << "The value of Fibonacci number " << input << " is " << current << endl;

	cin.ignore(2);
	return 0;
}

Make sure that this program executed correctly by running it and entering the value 12. You should get the number 144 as the 12th number of the Fibonacci sequence.
1. Set a breakpoint at the beginning of the for loop (the line containing for(….)) by clicking in the far left column of the edit frame. A red dot should appear when the breakpoint has been set.
2. Run the program and enter the value 46. The program should halt at the breakpoint. Click on the Locals tab at the bottom of the window to see the value of the local variables. What are the values of the program variables at this point?
i current back1 back2 input


3. Remove the breakpoint that was set in step 1 (by clicking on the red dot). Place a breakpoint on the line containing the closing curly bracket of the for loop. Right click on the breakpoint (red dot) and select Condition from the menu. Set the condition for this breakpoint to i == 9. Run the program. When it stops, record the value of the variables below.
i current back1 back2 input


4. Single step your program 4 times. Record the value of the variables below.
i current back1 back2 input


5. Using your conditional breakpoint, record the values of the variables in the table below for the values of i that are specified.
i current back1 back2 input
19
29
39
45

6. Allow the program to run to completion. Clear all breakpoints (by clicking on the red dot) except the conditional breakpoint at the end of the for loop. Run the program again, only this time with the input of 47. When the program stops, the variables should still have the same values as in the last line of the table from step 5, except the input variable should show 47. Now, single step your program 5 times and record the values of the variables.
i current back1 back2 input


7. Does anything seem wrong with your results? Explain what happened.



8. Change the data type of the back1, back2, and current variables to unsigned. Redo step 6 and record the values of the variables.
i current back1 back2 input


9. Explain why changing the data type corrected the problem.
 
Joined
Sep 10, 2008
Messages
532 (0.09/day)
Location
VA/PA
System Name Freyja
Processor Core i7 3770K
Motherboard AsRock Z77 Extreme4
Cooling Cooler Master Hyper 212 EVO
Memory 16 GB GSkill Sniper
Video Card(s) Diamond Radeon HD 7970
Storage Kingston HyperX 240 GB SSD + Seagate 2 TB HD
Display(s) Dell U2410
Case NZXT Tempest 210
Audio Device(s) Asus Xonar Essence STX
Power Supply Seasonic X-Series 750W
Software Ubuntu 13.04 64 bit
9. Explain why changing the data type corrected the problem.

Because the 47th Fibonacci number is larger than what a signed int can be :pimp:.
 
Joined
Dec 2, 2009
Messages
3,351 (0.64/day)
System Name Dark Stealth
Processor Ryzen 5 5600x
Motherboard Gigabyte B450M Gaming rev 1.0
Cooling Snowman, arctic p12 x2 fans
Memory 16x2 DDR4 Corsair Dominator Pro
Video Card(s) 3080 10gb
Storage 2TB NVME PCIE 4.0 Crucial P3 Plus, 1TB Crucial MX500 SSD, 4TB WD RED HDD
Display(s) HP Omen 34c (34" monitor 3440x1440 165Hz VA panel)
Case Zalman S2
Power Supply Corsair 750TX
Mouse Logitech pro superlight, mx mouse s3, Razer Basiliskx with battery
Keyboard Custom mechanical keyboard tm680
Software Windows 11
Benchmark Scores 70-80 fps 3440x1440 on cyberpunk 2077 max settings
Instead of int current use long long int current and you are in
That would mean like a google :p
I still want to know what book you make at school!

EDIT: I have a question myself:
I want to use the kanji japanese system in my c++ just for fun
Is there a way i can do it? I have learned that they take more
and use the unicode system so i don't know how to use it.
What should i do?
 

ctrain

New Member
Joined
Jan 12, 2010
Messages
393 (0.08/day)
An important note from other programmers to me was that system("pause")
is extremely worse. Instead use cin.get(); (it is 10 times faster)

it's the portability that is the problem more than the speed.

if you're using the STL already you might as well just use cin.get(); or cin.sync(); cin.ignore();
 
Top