Hey, I'm having a bit of trouble with my program. The issue isn't with the class I don't think, but rather the if statement. It's telling me that I have an else without a matching if statement. I get this error almost every time I make an if statement with an else. Can someone tell me what I'm doing wrong?
#include<iostream>
usingnamespace std;
class CoolSayingsClass
{
public:
void Saying1(){
cout << "This is the first saying";
}
void Saying2(){
cout << "This is the second saying";
}
void Saying3(){
cout << "this is the third saying";
}
};
int main()
{
int a;
cout << "Enter a number between 1 and 3";
cin >> a;
if (a=1)
{
CoolSayingsClass SayingOneObject;
SayingOneObject.Saying1();
}
elseif(a=2){
CoolSayingsClass SayingTwoObject;
SayingTwoObject.Saying2();
}
elseif(a=3);{
CoolSayingsClass SayingThreeObject;
SayingThreeObject.Saying3();
}
else{
cout << "You were supposed to enter a number between 1 and 3. I'm now going to terminate!";
}
return 0;
}
Extra semicolon on line 40. That condition would result in a no-op. Leaving just: { /*stuff*/ } else { /*stuff*/ }. So the compiler points out that you have an else without a matching if.
Hey thanks that made the program run, but now there's a new issue. No matter what is put in for a value between 1, and 3, only saying1 is shown. it's like only the saying1 function is called no matter what.
Checking out the program, I see you have assignment equals ( = ), instead of comparison equals ( == ).
I would only get Saying1, no matter what I inputted. To help learn more about Classes, myself, I added a Saying4, which actually is the last else. Also I made it so that to end the program, you must enter something other than 1 to 3. Thanks for helping me learn, too..
// Learning Classes.cpp : Defines the entry point for the console application.
#include<iostream>
usingnamespace std;
class CoolSayingsClass
{
public:
void Saying1()
{
cout << "This is the first saying";
}
void Saying2()
{
cout << "This is the second saying";
}
void Saying3()
{
cout << "This is the third saying";
}
void Saying4()
{
cout << "\nYou were supposed to enter a number between 1 and 3.\nI'm now going to terminate!\n\n";
}
};
int main()
{
int a=1;
CoolSayingsClass SayingObject;
while (a > 0 && a < 4)
{
cout << "Enter a number between 1 and 3 : ";
cin >> a;
if (a==1)
{
SayingObject.Saying1();
}
elseif(a==2)
{
SayingObject.Saying2();
}
elseif(a==3)
{
SayingObject.Saying3();
}
else
{
SayingObject.Saying4();
}
cout << "\n\n";
}
return 0;
}