• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.
  • The forums have been upgraded with support for dark mode. By default it will follow the setting on your system/browser. You may override it by scrolling to the end of the page and clicking the gears icon.

C++ programming

Joined
Dec 2, 2009
Messages
3,353 (0.59/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:
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?
 
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.
 
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;				
}
 
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;
    		
}
 
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?
 
cout << "\nEmployee: " << first<<" " << last << endl
 
AHH! That worked like a charm. So input "" marks for spaces in output code.
 
no, " " white space :D
 
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.
 
@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
 
@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?
 
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:
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;

}
 
@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)
{
 
An important note from other programmers to me was that system("pause")
is extremely worse. Instead use cin.get(); (it is 10 times faster)
 
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.
 
Subbing because I may need to use this thread in the future, seeing as I'm currently in a C++ class right now :D.
 
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.
 
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:.
 
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?
 
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();
 
Back
Top