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;
usingnamespace 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.
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().
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>
usingnamespace 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.