Simple code not working

I have been learning c++ for about an hour now and i have produced this code. It is meant to print the number 7 in the command prompt but it does not and i cant figure out why. Can anyone help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "stdafx.h"
#include <iostream>

int x;
int y;
int main()
{
	x = 5;
	y = x + 2;
	using namespace std;
	cout << y << endl;
	cin.clear();
	cin.ignore(255, '\n');
	cin.get();
	return 0;
}
Sorry, i for got to explain that i am getting no error. I need it to print the variable y, which should be 7 as it is x + 2. But it is printing 5 for some reason.
Hm, I just tested it on VC++ 2008 and it printed 7 as expected...what compiler/IDE are you using?
Microsoft Visual C++ 2010 Express
Is this really the exact code you're using? Try a rebuild too.
And although it's not related to the problem directly, you should not declare your variables in global scope, but rather in main().
I just tried rebuilding and i moved the declarations into main() but it still only shows 5. And yes i am using exactly that.
Last edited on
That is quite strange...You sure you aren't accidentally printing x instead of y?
Create a new project again, but this time instead of clicking FINISH, click NEXT and then make sure you check "empty project" so there's no stdafx header file. Now right click source files and make a new one (name it whatever you want) and add this code...
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
	int x = 5;
	int y = x + 2;
	cout << y << endl;
}

Now press CTRL+F5 to build and run it. This should fix whatever problems you were having. I am assuming that you're beginning to learn c++ through some type of book/documentation (correct me if I'm wrong) and you want to get into the habit of making sure it's an EMPTY project when you follow their code.
Last edited on
That worked perfectly, thank you.

And yes i am following a tutorial XD. This one to be exact. http://www.learncpp.com/

Topic archived. No new replies allowed.