Need an If before Else Error.

-OverpoweR-

Member
Reaction score
13
Ellow guys, i've been messing around and also got the Code Blocks now, and i've been trying to work out with this code,

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string answer=("Yes","yes","No","no");
    string operation=("Multiply","multiply","Summarize","summarize","Substract","substract","Divide","divide");
    int x,y;


    cout << "Hello,my name is Alpha,please state your name before we continue: " << endl;
    string name;
    cin >> name;
    cout << name << ", Good to meet you. Shall we Continue? (Yes or No) " << endl;
    cin >> answer;

    if(answer=="Yes","yes"){cout << "Alright " << name << " what would you like to do? (Multiply,summarize,substract,divide)"  << endl;}
    else{
        if(answer=="No","no"){cout << "Alright " << name << " Hope to talk with you soon again. Have a good time!" << endl;} }

        cin >> operation;

        if(operation=="Multiply","multiply"){cout << "Please give me your first integer: " << endl; }
        cin >> x;
        cout << x << ",alright now give me your second integer: " << endl;
        cin >> y;
        cout << x*y << " There you go, anything else?(Multiply,summarize,substract,divide"  << endl;
        cin >> operation;

        else{
            if(answer=="Summarize","summarize"){cout << "Summarizing eh? Ok,give me your first integer: " << endl;}
            cin >> x;
            cout << x << ",and your second integer?" << endl;
            cin >> y;
            cout << x+y << ",there's your result! Got anything more challenging for me?(Multiply,summarize,substract,divide)" << endl;
            cin >> operation;}

            else{
            if(answer=="Substract","substract"){cout << "Oh i love substracting, give me your first integer: " << endl;}
            cin >> x;
            cout << x << ", and your second integer?" << endl;
            cin >> y;
            cout << x-y << ", hows that for super speedy answer! Do you have anything else that you need me to do?(Multiply,summarize,substract,divide)" << endl;
            cin >> operation;}

            else{
            if(answer=="Divide","divide"){cout << "Division, hmmmm, alright,give me your first integer: " << endl;}
            cin >> x;
            cout << x << ",what would your second integer be?" << endl;
            cin >> y;
            cout << x/y << ",i think i did right! I hate division... well" << name << " got anything else for me?(Multiplay,summarize,substract,divide)" << endl;
            cin >> operation; }



    return 0;

}

I've been struggling for an hour now but i cant seem to figure a fix for this, these are the only errors that im getting while trying to compile:

D:\PROGRAMMING SECTION\InteractiveCalculatro vCodeBlocks\Interactive Calculator\main.cpp|32|error: 'else' without a previous 'if'|

D:\PROGRAMMING SECTION\InteractiveCalculatro vCodeBlocks\Interactive Calculator\main.cpp|40|error: 'else' without a previous 'if'|

D:\PROGRAMMING SECTION\InteractiveCalculatro vCodeBlocks\Interactive Calculator\main.cpp|48|error: 'else' without a previous 'if'|


Would anyone be kind enough to spare some time and guide me through this? and/or give me some feedback on efficiency of this code :(

Nevermind, got it :)

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string answer=("Yes","yes","No","no");
    string operation=("Multiply","multiply","Summarize","summarize","Substract","substract","Divide","divide");
    int x,y;


    cout << "Hello,my name is Alpha,please state your name before we continue: " << endl;
    string name;
    cin >> name;
    cout << name << ", Good to meet you. Shall we Continue? (Yes or No) " << endl;
    cin >> answer;

    if(answer=="Yes" || "yes"){cout << "Alright " << name << " what would you like to do? (Multiply,summarize,substract,divide)"  << endl;}
    else{
        if(answer=="No" || "no"){cout << "Alright " << name << " Hope to talk with you soon again. Have a good time!" << endl;} }

        cin >> operation;

    if(operation=="Multiply" || "multiply")
    {cout << "Please give me your first integer: " << endl;
        cin >> x;
        cout << x << ",alright now give me your second integer: " << endl;
        cin >> y;
        cout << x*y << " There you go, anything else?(Multiply,summarize,substract,divide)"  << endl;
        cin >> operation;}
    else{
            if(answer=="Summarize" || "summarize")
            {cout << "Summarizing eh? Ok,give me your first integer: " << endl;
            cin >> x;
            cout << x << ",and your second integer?" << endl;
            cin >> y;
            cout << x+y << ",there's your result! Got anything more challenging for me?(Multiply,summarize,substract,divide)" << endl;
            cin >> operation;}
    else{
            if(answer=="Substract" || "substract")
            {cout << "Oh i love substracting, give me your first integer: " << endl;
            cin >> x;
            cout << x << ", and your second integer?" << endl;
            cin >> y;
            cout << x-y << ", hows that for super speedy answer! Do you have anything else that you need me to do?(Multiply,summarize,substract,divide)" << endl;
            cin >> operation;}
    else{
            if(answer=="Divide","divide")
            {cout << "Division, hmmmm, alright,give me your first integer: " << endl;
            cin >> x;
            cout << x << ",what would your second integer be?" << endl;
            cin >> y;
            cout << x/y << ",i think i did right! I hate division... well" << name << " got anything else for me?(Multiplay,summarize,substract,divide)" << endl;
            cin >> operation; } } } }



    return 0;

}
 

DrEvil

FCRI Associate!
Reaction score
111
if(answer=="Yes" || "yes")
does this even work? I'm sure that both sides need to have a comparison (and then either one side has to be true to continue):
if(answer=="Yes" || answer=="yes") ?

also in the last cout statement there is:
"cout << x/y << ",i think i did right! I hate division... well" << name << " got anything else for me?(Multiplay,summarize,substract,divide)" << endl;"

where it would output something as "...I hate division... wellSteve got anything..."
kinda shows you haven't tested it, although its simple and shows no error to the eye ;)

another "if(answer=="Divide","divide")" which wasn't changed.

endl can be removed and replaced with a "\n" at the end of your text to signify a line break:
cout << "Hello world!\n";
It is quicker to type "\n" than << endl and easy to remember

when using if statements if only one operation is being used/called after it you don't need brackets:

if(myInt==5)
...cout << "int ==5!" << endl;

as opposed to more operations:

if(myInt==5){
...cout << "myInt nolong equals 5!" << endl;
...myInt=4;
}

I don't know if it's the forums text screwing up but keeping a standard to yourself on how to layout code should be implemented:

if(true){
...if(true)
......cout << "It's true!\n";
...//indented by a tab (3 spaces?)
...//each layer of if() or while() would be indented another tab(3 spaces?)
...cout << "Still true...\n";
}

I also saw : "(Multiply,summarize,substract,divide" << endl;
Any reason for an open bracket and no closing bracket?
And Multiply has a capital and the others don't :s
They may be feeling sad... operations have feelings too!

I'm no way a pro, but just some things that I could point out :)
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
Code:
if (answer=="Yes" || "yes")

This compiles fine, but it will ALWAYS ALWAYS ALWAYS return true. Always.
That's an error I've seen other beginners make too.

This condition first checks if answer equals "Yes" (that's alright so far).
Next it checks if "yes". It doesn't check if answer equals "yes" but simply checks "yes".
For this kind of case C++ will get the memory address of whatever you've written. So the compiler will interpret it like this:

Code:
if (answer == "Yes" || 0x23465 ) //this would be the memory address of the cstring "yes"

Now, what happens if you only write if ( <any number> )? It'll implicitely compare it to 0. So it'll become if ( <any number> != 0 ). The memory address of "yes" is guaranteed to be non-zero. So it'll become if ( <any non-zero number> != 0 ). So it's equivalent to if ( true ).
In the end you have (answer == "Yes" ||true) which will always be true, of course.

The solution is, like DrEvil said, to write if( answer == "Yes" || answer == "yes" )

However, what happens if the user enters "YES"? Or any other variation? It would be much easier to just convert answer into a lower-case-string and then just check for answer == "yes".

That would be a bother - if we did not have the standard library!

Code:
#include <algorithm> //Needed header

 transform(answer.begin(), answer.end(), answer.begin(), tolower);
}

The transform command converts the entire answer string (from begin to end) to be turned into lower case.
So now we could write:

Code:
transform(answer.begin(), answer.end(), answer.begin(), tolower);
if(answer== "yes"){
 ....
}


Writing this does something similarily aweful:
Code:
    if(answer=="Divide","divide")

The result is the same as (answer == "Divide" || "divide"), just because of a different reason.
You're using the comma operator here, something you have to be very aware of.
The way the comma works is that it evaluates it's left-hand expression, throws it's result away(!) and the evaluates the right-hand expression.
So the above code turns into if( "divide" ) because the rest is thrown away by the comma. Now it's the same thing as above, where the address of "divide" will be taken and compared against 0. In the end this will also always return true.

If you answer your program's questions with neither some random phrases like "blabaltladfgldr" you'll see that it still acts like you said "yes". That's because of these errors inside your if-statements.

Same goes for your variable initialisation:
Code:
string answer=("Yes","yes","No","no");

Again, the comma operator will throw all but the right-most expression away. So this above is equivalent to writing string answer = ("no");, which again is (in practice) equivalent to string answer = "no";.

I'm not sure why you even wrote this line. Did you want to say that answer can take one of the following values? That's not possible like that in C++.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • WildTurkey WildTurkey:
    is there a stephen green in the house?
    +1
  • The Helper The Helper:
    What is up WildTurkey?
  • The Helper The Helper:
    Looks like Google fixed whatever mistake that made the recipes on the site go crazy and we are no longer trending towards a recipe site lol - I don't care though because it motivated me to spend alot of time on the site improving it and at least now the content people are looking at is not stupid and embarrassing like it was when I first got back into this like 5 years ago.
  • The Helper The Helper:
    Plus - I have a pretty bad ass recipe collection now! That section of the site is 10 thousand times better than it was before
  • The Helper The Helper:
    We now have a web designer at my job. A legit talented professional! I am going to get him to redesign the site theme. It is time.
  • Varine Varine:
    I got one more day of community service and then I'm free from this nonsense! I polished a cop car today for a funeral or something I guess
  • Varine Varine:
    They also were digging threw old shit at the sheriff's office and I tried to get them to give me the old electronic stuff, but they said no. They can't give it to people because they might use it to impersonate a cop or break into their network or some shit? idk but it was a shame to see them take a whole bunch of radios and shit to get shredded and landfilled
  • The Helper The Helper:
    whatever at least you are free
  • Monovertex Monovertex:
    How are you all? :D
    +1
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top