OK, so, I'm a beginner in C++ programming and while I was just testing myself, I decided to create a simple program that when I enter the number "3000", it will say "Yeah right!" and when I enter another number (any number but "3000"), it will say "What the heck?". So I came up with this:
#include <iostream>
using namespace std;
int main()
{
int Number;
cout<<"Please enter a number: ";
cin>> Number;
cin.ignore();
if (Number == 3000);
cout<<"Yeah right!\n";
else;
cout<<"What the heck?\n";
cin.get();
}
But, when I try to build it, it keeps on saying ""Else" without a Previous "If". What the heck should I do now? It's driving me NUTS!! And btw, I'm using Code::Blocks.
See that semi-colon at the end there? That' the END of what the if statement will execute if the condition is true. Similar with your else. Try this instead:
Well you do not use ";" before your if statement body function.
So for example this :
1 2 3 4
if (Number == 3000);
cout<<"Yeah right!";
else;
cout<<"What the heck?";
Should be something like this :
1 2 3 4 5
if (Number == 3000) {
cout<<"Yeah right!";
} else {
cout<<"What the heck?";
}
or this :
1 2 3 4
if (Number == 3000)
cout<<"Yeah right!";
else
cout<<"What the heck?";
Also spacing wouldn't hurt your code and would make it more readable.
For example this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int Number;
cout<<"Please enter a number: ";
cin>> Number;
cin.ignore();
if (Number == 3000);
cout<<"Yeah right!";
else;
cout<<"What the heck?";
cin.get();
}
into this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int Number;
cout << "Please enter a number: ";
cin >> Number;
cin.ignore();
if (Number == 3000) {
cout << "Yeah right!";
} else {
cout << "What the heck?";
cin.get();
}
}
also why are you using cin.get() and cin.ignore() for this?
But the main reason you were getting that error is because you had a ";" at the beginning of your if statements body and after the else.