Simple Code failing

closed account (LTXN8vqX)
I have been window gui's with winapi and game hacks, but i suddenly realized that i don't fully understand everything. So i quit hacking and crap like that and now i am trying to restudy c++. So i wanted to make a program that would print every other letter of a string, but it ended up printing random characters. Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
	char szbuffer[10]="hello how";
	for(int i = 0; i = sizeof(szbuffer); i+=2){ 
	cout<<szbuffer[i];
	if(i = 10){break;}
	
	}
	cin.get();
	return 0 ;
}


Line 6... your condition is wrong:

i = sizeof(szbuffer);

You probably meant this:

i < sizeof(szbuffer);


You also have the same problem on line 8:

if(i = 10){break;} // you probalby meant i == 10

Remember that = is assignment. In both cases you are reassigning the value of i so that it is something else. You don't want to do that in either or those situations.
The format is: for (initialization; condition; increase) statement;
ref: http://www.cplusplus.com/doc/tutorial/control/

...printing random characters.

you first declare i = 0, then you change it to i = sizeof(szbuffer), so your cout will start printing from szbuffer[sizeof(szbuffer)] which gives you garbage.
you're lucky because you make another mistake in if(i = 10) break; which cause your loop to exit ;)
Last edited on
Your problem is the for loop.

Look here: http://cplusplus.com/doc/tutorial/control/

Also, the if statement will not do what you expect it to.

1
2
3
4
5
6
7
//Right way:
int a = 0; // one '=' for assignment/definition
if(a == 1) { } // two '='s for comparison

// Wrong way:
int a = 0;
if(a = 2) { } // sets a equal to 2 and returns true (the code within the if statement will always be run) 


That if statement will be redundant when you fix the for loop anyway.
Last edited on
Topic archived. No new replies allowed.