C++: How can I update a variable

This is a discussion on C++: How can I update a variable within the C++ Programming forums, part of the General Programming Boards category; Hi, I've been doing C++ for about 2 hours now, so please don't confuse me much, i've been working on ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    4

    C++: How can I update a variable

    Hi, I've been doing C++ for about 2 hours now, so please don't confuse me much, i've been working on a small game to test variables and loops. I've got a woking script for now, but am stuck with the integers of a and x updating when both the character and enemy receive damage. I can do it manualy by adding more loops where with each hit, it forces the integers a and x to change, but for when I want to get more into it and add potions, exp gaining and stat boosting it will be a whole load of loops and will eventually get too confusing for me. So can someone let me know of how I can get integers a and x to continiously updates each time they receive damage, thanks.

    Code:
    #include <iostream>
    #include <string>
    
    int subtract(int x, int y)
    {
     return x-y;
    }
    
    int subtracta(int x, int z)
    {
    	return x-z;
    }
    
    int subtractb(int a, int b)
    {
    	return a-b;
    }
    
    int subtractc(int a, int c)
    {
    	return a-c;
    }
    using namespace std;
    
    int main()
    {
     int x(100), y(5), z(10), a(10), b(5), c(2);
     string answer;
    
     for (int (x < 100); int (x > 0); x){
    	 cout<<"would you like to hit or block the enemy? ";
    	 cin>>answer;
    	 if (answer=="hit") {
    		 cout<<"you have hit the enemy\n";
    		 cout<<"the enemy has "<<subtractb(a, b)<<" hp\n";
    		 cout<<"your hp is now "<<subtracta(x, z)<<"\n";
    	 }
    	 else if (answer=="block"){
    		 cout<<"the enemy has hit you\n";
    		 cout<<"the enemy has "<<subtractc(a, c)<<" hp\n";
    		 cout<<"your hp is now "<<subtract(x, y)<<"\n";
    	 }
    	 else {
    		 cout<<"you can only hit or block, try again\n";
    	 }
    	 cin.get();
     }
    }

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    To update a variable you usually use the = sign. Ex.
    Code:
    a = 50;
    As for this for loop:
    Code:
    for (int (x < 100); int (x > 0); x)
    Does that even compile? What's with all the int's? Since the 3rd part of the for loop does nothing, it should be an infinite loop. Usually you change the value being compared like ++x or --x or x += 5...

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Um. Yes. Well, I don't know where you're learning C++ from (and don't tell me, because I want to keep it that way), but some things that they didn't tell you or you forgot to read:
    1. Assignment operator. It looks like =. The value on the right is then placed into the variable on the left. For instance, the statement "a=a-x;" computes the value a-x and puts the value in the variable a.
    2. Variables. Each variable is local to the function in which it is declared, so the x in main is not the same x as the x in subtract. (And, as an additional bonus in this case, that means that each of your four functions is exactly the same function. Exciting!)
    3. Loops. I don't know what you think a for loop is good for, but that isn't it. I also don't know what you think int (x < 100) does, but that isn't it, either.

    So: whatever book or tutorial you're reading, stop and go back to page 1/part 1. This way, you'll know what all the words that you are slinging around actually mean.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    4
    Quote Originally Posted by cpjust View Post
    As for this for loop:
    Code:
    for (int (x < 100); int (x > 0); x)
    Does that even compile?
    Yes it compiles perfect and works with looping, 'hit' and 'block', the only problem that I get, is if I use 'hit' it will display the stats fine, with character hp being 90 and enemy hp being 5, however if when the loop comes back to ask me again, it will reset and character hp being 90 again and enemy hp being 5 still. Similar if I use 'block' the character hp will reset to 100 then decrease by 5 showing 95, and enemy hp will reset to 10 then decrease by 2 showing 8.

    So from what I can tell, its working but the variables aren't updating, I don't know how to do it. One method I read was to use
    Code:
    (x < 100); int (x > 0); (x++))
    which works, but each time the character hp increases by 1 rather than continue to decrease.

    that command
    Code:
    (x < 100); int (x > 0); x)
    is just saying that, while character hp (x) is under 100 [the starting hp] and above 0 [or he would be dead] to continue looping.

    Quote Originally Posted by tabstop View Post
    I also don't know what you think int (x < 100) does, but that isn't it, either.
    stop and go back to page 1/part 1.
    you are slinging around actually mean.
    I answered the first one for you, and I understand what it means, it is this loop:
    Code:
    [for ( variable initialization; condition; variable update ) {
      // Code to execute while the condition is true
    }
    So its obvious that part of that, the 3rd portion is meant for the update, but I don't know what to do. The reason why I used that, is for the 1st portion which is meant for initialization, when the character gains xp or a stat boost to hp, then it will move onto the next loop accourding to the hp.
    Last edited by nekkron; 12-11-2007 at 09:11 PM.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by nekkron View Post
    that command
    Code:
    (x < 100); int (x > 0); x)
    is just saying that, while character hp (x) is under 100 [the starting hp] and above 0 [or he would be dead] to continue looping.
    No. No it doesn't say that in any way, shape, or form. I hate to say it, but no you don't understand anything you have written.

    Quote Originally Posted by nekkron View Post
    I answered the first one for you, and I understand what it means, it is this loop:
    Code:
    [for ( variable initialization; condition; variable update ) {
      // Code to execute while the condition is true
    }
    At least you have correctly quoted something.
    Are you trying to tell me that int (x<100) is supposed to be variable initialization? Are you seriously claiming that "x" is a variable update?
    You used an interesting word in your description above--twice, in fact. That word is "while". That may be construed as a hint.

    Meantime, two of us now have told you about =. How are you learning C++? What possible course of action could you take that would allow you to properly write functions (four of them!), but not use = ? I've changed my mind; I do want to know what book or tutorial or whatever you're learning C++ from, so I can point out that what you're asking about is covered in chapter 2 while you're using things from chapter 8.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Quote Originally Posted by cpjust View Post
    As for this for loop:
    Code:
    for (int (x < 100); int (x > 0); x)
    Does that even compile? What's with all the int's? Since the 3rd part of the for loop does nothing, it should be an infinite loop. Usually you change the value being compared like ++x or --x or x += 5...
    It'll compile. int(x<100) is interpreted as a cast from bool to int. same for int(x>0).

    Quote Originally Posted by nekkron View Post
    So from what I can tell, its working but the variables aren't updating, I don't know how to do it. One method I read was to use
    Code:
    (x < 100); int (x > 0); (x++))
    which works, but each time the character hp increases by 1 rather than continue to decrease.

    that command
    Code:
    (x < 100); int (x > 0); x)
    is just saying that, while character hp (x) is under 100 [the starting hp] and above 0 [or he would be dead] to continue looping.
    the proper syntax for that condition is:
    x<100 && x>0
    The condition goes between the two semicolons in a for loop.

    Code:
    [for ( variable initialization; condition; variable update ) {
      // Code to execute while the condition is true
    }
    So its obvious that part of that, the 3rd portion is meant for the update, but I don't know what to do. The reason why I used that, is for the 1st portion which is meant for initialization, when the character gains xp or a stat boost to hp, then it will move onto the next loop accourding to the hp.
    Tabstop is right, whatever source you're using to learn C++, stop. Get yourself a book.

    In the meantime here's a wiki link to all C++'s operators. Learn how to use them. In this case, -=, =, and both versions of -- are possible ways to decrease x.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Registered User
    Join Date
    Nov 2007
    Posts
    40
    Quote Originally Posted by tabstop View Post
    You used an interesting word in your description above--twice, in fact. That word is "while". That may be construed as a hint.
    That.. was so.. awesome. I laughed irl.

    Nekkron, you may want to hit the books again. The BEGINNING of the books.

    PS: Use a "while" loop.

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Congratulations, you have four identical functions. Absolutely 100% identical!

    That loop you've got there would be of the infinite variety.

    Would you be surprised to learn that 'answer' is the only variable in that program that ever changes value?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    Quote Originally Posted by nekkron
    I've been doing C++ for about 2 hours now, so please don't confuse me much
    nekkron,

    You are jumping-in head first and trying to write a program before learning the language. Enthusiasm is good, but this is going to get very frustrating for you, and for anyone here trying to help you.

    SLOW DOWN! work-through the tutorial and get a good beginning C++ book. Once you understand variables, functions, loops, and if-statements, you can start to write interesting programs that "do something".

    Quote Originally Posted by DougDbug
    Develop your code a few lines at a time.

    Someday I'm going to write an essay on this topic. It seems like a lot of instructors don't really teach how to approach a programming problem. This result in lots of frustrated beginners & students. Nobody... not even experienced programmers write the whole program before trying it out!

    1- Start-out with a 'Hello World" type program. You can substitute "Hello World" with some better description of the program.

    2- Add one or two lines of code at a time. Compile, test-run, and debug before adding more lines.

    3- Add some extra cout statements so you can "see" what the program is doing, and confirm that it's working, before you're completely done. (You can take them out, or coment them out later.)

    4- When you create a function, make an empty (do-nothing) function first. Make the function prototype, the empty function definition, and the function call. Then, test-compile. If your function needs to return a value, just make it return a constant (i.e. return 10; ). It's also helpful to put a cout statement in your do-nothing function like: cout << "Now in FunctionOne() \n"; .

    Now, this isn't as easy as it sounds, because you can't just write line one, then line two, then line three, of your code. (It won't compile if you do that.) The trick (the fun part, actually) is figuring-out which part of code makes sense to work on next.

    Compilers can easily get confused when threre's an error (or two). Sometimes they will point to the wrong line. Sometimes one real error will cause the compiler to report several errors. Link errors are even trickier to track down.

    So, it really helps to test-run and test-compile after every one or two lines. As you gain experience, you can write whole functions before testing. But, as you gain experience your programs generally will get longer and more complex, so you still won't be writing the whole program before testing & debugging.
    Last edited by DougDbug; 12-12-2007 at 02:45 PM.

  10. #10
    Registered User
    Join Date
    Dec 2007
    Posts
    4
    Haha, thanks guys, yes of course I jumped in head first, it's what I do whether correct or not you still learn from mistakes. DougDbug, I am writing it from the start, this is the beginning of the application, i'm intending to make one similar to a Game RPG system where after a while the HP will increase in total based on EXP gained. Anyway, I don't completely understand what was mostly said about what to use instead, but I do know of the 'while' loop, in my instance being;

    Code:
    { 
      int x = 0;  
      while ( x => 0 ) {
        cout<< x << endl;
      }
    }
    I'm not sure I understand the 'endl' though, i've tried it and it seems to stop the loop, if I remove it the loop continues. Yes, actually where I got that 'for' loop was from this site, i've been using it to learn, and still at the beginning since i've had two 12 hour days in a row I haven't had much time to revise it. So it would make more sense to use a 'while' loop anyway since I only have to declare 'x' variable to be more than or equal to '0'. For another part then, iMalc, what do you mean when you say "four identical funtions"? Are you refering to these parts?

    Code:
    int subtract(int x, int y)
    {
     return x-y;
    }
    Because even from my very limited knowledge, each function there is doing something different; they are all decreasing the x and a values depending on which word I use 'hit' or 'block' when I test it currently it works like I said. Unless of course you are refering to this

    Code:
    cout<<"the enemy has "<<subtractb(a, b)<<" hp\n";
    Where again, each time it is doing something different, 2 are for the enemy and 1 for the character, and depending on whether 'hit' or 'block' are used, it would decrease the values by different amounts.

    Anyway, i'm sorry if I don't need the long explanations, but it's helping me to read through what i'm writing to make sure it makes sense enough to understand what I mean. If a 'while' loop is the better option, which I will try out now, will that properly update the variables or am I still missing something?

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,897
    Quote Originally Posted by nekkron View Post
    Code:
    { 
      int x = 0;  
      while ( x => 0 ) {
        cout<< x << endl;
      }
    }
    While loop will go on forever because value of x never changes. So x == 0 all the time, and so it continues to loop.
    Oh and that's a syntax error. => should be >=.
    endl is the same as '\n' figuratively speaking, because they do the same thing - print a new line.

    For your functions, I'd say get rid of them. Just do normal +, -, * and /. The thing is also that just because you pass a and b to the functions, local copies are made and you never store the result so, it's kindof like this:

    Code:
    int a = 1, b = 2;
    a + b;
    See? You never store the result, so a and b will never change.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Dec 2007
    Posts
    4
    Thanks, thats starting to make sense now. Still a little bit puzzled about using a loop though, i'm still testing out various functions and what they can do, so hopefully I can find a way to do it all.

    EDIT: I've found a use for the 'for' loop, and this script isn't meant for it, the 'while' works perfect, with some more addons i've done more functions so my new code is like this:
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	string answer;
    	string name;
    	string e1;
    	string build;
    	int x(100); // char base hp
    	int y(30); // enemy base hp
    	int a(2); // char base blo.
    	int b(5); // char base att.
    	int c(1); // char secondary blo.
    	int d(4); // char secondary att.
    
    
    	cout<<"what is your name? ";
    	cin>>name;
    	cout<<"what would you like to call the enemy? ";
    	cin>>e1;
    	cout<<"what stat build would you prefer?\n";
    	cout<<"build 1: +5 att. +1 block. +20 hp.\n";
    	cout<<"build 2: +1 att. +3 block. +40 hp.\n";
    	cout<<"build 3: +3 att. +5 block. +60 hp.\n";
    	cin>>build;
    	if (build=="1"||"build 1") {
    		(b=10); // inc. att. +5
    		(a=3); // inc. blo. +1
    		(d=9); // inc. secondary att. +4
    		(c=2); // inc. secondart blo. +0
    		(x=120); // inc. hp +20
    	while (x >= 1&&y >= 1) {
    	cout<<"do you want to hit or block "<<e1<<"? ";
    	cin>>answer;
    	if (answer=="hit") {
    			cout<<e1<<" recieved "<<(b)<<" damage\n";
    			cout<<name<<" revieved "<<(a)<<" damge\n";
    			(--x);
    			(--x);
    			(--x);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    	}
    	else if (answer=="block") {
    			cout<<e1<<" recieved "<<(d)<<" damage\n";
    			cout<<name<<" revieved "<<(c)<<" damge\n";
    			(--x);
    			(--x);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    	}
    	else {
    		cout<<"please use only hit or block\n";
    	}
    	cout<<"\n";
    	cout<<name<<" has "<<(x)<<" health remaining\n";
    	cout<<e1<<" has "<<(y)<<" health remaining\n";
    	cout<<"\n";
    	}
    	}
    	cin.get();
    }
    My full script, has 3 different character builds, and I'm still unable to work out how to update the stat variables based on which character build I choose, they all seem to use the first build. I think perhaps a 'while' loop with 'do' constraint would work, but i'm not sure. So more trial and error for me. But thanks for the info it works fine.
    Last edited by nekkron; 12-13-2007 at 08:57 AM.

  13. #13
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Code:
    (--x);
    (--x);
    (--y);
    (--y);
    (--y);
    (--y);
    (--y);
    (--y);
    (--y);
    (--y);
    (--y);
    You can condense this into 2 lines:
    Code:
    x -= 2;  // Same as:  x = x - 2;
    y -= 9;  // Same as:  y = y - 9;

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,897
    Your indentation still needs some improvement. For example, that if... it's hard for me to see where it actually ends because you've failed to indent the code in that block properly.
    The rule is to always do indention at each new block (things that begin with { and end with }).
    Now, as for the code...

    Quote Originally Posted by nekkron View Post
    Code:
    	int x(100); // char base hp
    	int y(30); // enemy base hp
    	int a(2); // char base blo.
    	int b(5); // char base att.
    	int c(1); // char secondary blo.
    	int d(4); // char secondary att.
    I'm assuming you're initializing these variables? I'd rather prefer to see int x = 100, because it's much clearer what you're trying to do. I almost mistook it that you wanted to write an array. So think about it a little.

    Code:
    	if (build=="1"||"build 1") {
    If doesn't quite work that way.
    It's If (condition1 || condition2). That line might just give you a warning, because "build 1" is a const char*, which is always != 0, thus always true. Thus the IF will always execute. You should do if (build == "1" || build == "build 1") or something depending on what you want.

    Code:
    		(b=10); // inc. att. +5
    		(a=3); // inc. blo. +1
    		(d=9); // inc. secondary att. +4
    		(c=2); // inc. secondart blo. +0
    		(x=120); // inc. hp +20
    This does not do what you think it does. It assigns 10 b, 3 to a, 9 to d, 2 to c and 120 to x. If you want to increase it, just do a += 3 or a = a +3 (basic math!). And use better variables names. b, a, d, c, x... well, they just don't tell me anything that's stored in those variables at all.

    Code:
    			(--x);
    			(--x);
    			(--x);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    I'm also confused, besides what cpjust mentioned, why you decrement those variables so many times. Also, basic math applies here as well: y = y - 10 or y -= 10.

    Code:
    			(--x);
    			(--x);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    			(--y);
    Same here...
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by Elysia View Post
    Your indentation still needs some improvement. For example, that if... it's hard for me to see where it actually ends because you've failed to indent the code in that block properly.
    I don't know if the code was updated since you posted this, but the if statements look indented to me (albeit a little too indented for my taste).

    Quote Originally Posted by Elysia View Post
    I'm assuming you're initializing these variables? I'd rather prefer to see int x = 100, because it's much clearer what you're trying to do. I almost mistook it that you wanted to write an array. So think about it a little.
    You're right, it is a bit strange to see this type of initialization for primative types like int, but as for classes, I use constructor initialization as much as possible rather than assignment since it just seems like a waste to default construct an object and then change the state right afterwards.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 09-27-2005, 01:49 PM
  2. variable being reset
    By FoodDude in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2005, 01:30 PM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. About classes and HINSTANCE variable to Main
    By conright in forum Windows Programming
    Replies: 2
    Last Post: 01-01-2003, 08:00 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21