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.
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/
  • The Helper The Helper:
    Here is another comfort food favorite - Million Dollar Casserole - https://www.thehelper.net/threads/recipe-million-dollar-casserole.193614/

      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