I am new and beginner in programming and dont quiet understand how to post my question here. Hope this works.
Anyways, im starting from basic and just learnt the "if" statement. But when i tried to create my own version its not working. My program below is showing all three cout results even if i enter only one option(attack or run or hide). It was working fine when there was just one "if" statement. I tried the "else if" too but then it only printed out the result "you have attacked" no matter what i chose. :( I used the search bar for similar questions that might have already been answered but didnt find much that could help me.
If there are similar questions then i'd appreciate if you could point me towards it, although i'd really be grateful if you could point out what my mistakes are specifically.
Thnx~
#include <iostream>
#include <string>
using namespace std;
int main(){
cout<<"Welcome to the jungle!!!"<<endl;
cout<<"--------"<<endl;
cout<<"Enemies approaches! \n Choose your next move! \n";
cout<<"Attack / Run / Hide \n\n\n";
string choice;
cin>>choice;
if(choice=="Attack"||"attack")
{
cout<<"You have attacked!"<<endl;
}
if(choice=="Run"||"run")
{
cout<<"You start running!"<<endl;
}
if(choice=="Hide"||"hide")
{
cout<<"You hide in a cave!"<<endl;
}
return 0;
}
if(choice=="Attack"||"attack")
does not mean "if choice contains "Attack", or choice contains "attack", do the thing".
It means "if choice contains "Attack", or "attack" is true, do the thing".
In pseudo-code, you expect:
if choice is the string "Attack"
or choice is the string "attack"
do a thing
but the or splits the statement into halves, and the second half doesn't mention the variable choice at all. It breaks down more like
if choice is the string "Attack"
or the string "attack" on its own is somehow true, whatever that might mean
do a thing
Since "attack" is a pointer to a char array, being true means it is not NULL, which is always the case, so this branch is always entered.
To express what you mean, write instead:
if(choice=="Attack"||choice=="attack")
Welcome to C/C++ world.
As you have already read in tutorials or book, the content inside the parens of an if has to be a boolean value. Now, a lot of stuff can be converted automatically to bool and as a condition for an if.
In particular, anything that can be converted to an int will, in turn, have a bool value attached to it. Pointers are of such kind.
If the value is different from 0 then the result will be -> true
0 otherwise.
Writing if(choice=="Attack"||"attack") you are telling the compiler to execute the content of the if either if the content of choice is equal to the string Attack or if the the pointer to the underlying const char* attack is not zero.
attack is a valid string which mean its value is not zero which in turn means you are getting a true out of it.
Same goes for all the others ifs. The second part of all you ifs are true cause they are not null pointers.
Change the all the ifs as the following: if(choice=="Attack"||choice=="attack") and the problem will be fixed.
You must use
if(choice=="Attack"||choice=="attack")
{
cout<<"You have attacked!"<<endl;
}
OR( || ) is a boolean operator.
So Anything other than 0 gives an impression of 1 in boolean. Thus the syntax in if code is always executed. This is the reason for in the else if case first statement is always executed (and further statements are skipped).
Also, using namespace std; is a bad practice since it makes our code confined to just one std library. instead you must use std:cout;
Related
if(!word.size()){
return true;
}
whole code screenshot
how here use string.size() lonely to return a boolean value?
I googled the string.size() method although i already know it returns a int value,but here it works like a true/false method;
Lots of things in C++ can be coerced to Booleans. Off the top of my head.
Booleans are trivially convertible to Booleans
Numbers (int or double) can be converted to Boolean; zero is false and anything else is true
Streams (like fstream instances or cout, for instance) can be converted to Boolean and are true if the stream is in "good" condition or false if there's a problem
As indicated in the comments, you shouldn't use this in real code. if (!word.size()) is silly and confusing an should only be seen in code golf challenges. Coding isn't just about making the computer understand what you mean; it's about making sure future readers (including yourself six months down the line) understand as well. And if (word.empty()) conveys the exact same intent to the computer but is much more understandable to the human reader at a glance.
So why does C++ allow this if it's discouraged? Historical reasons, mostly. In the days of C, there was no dedicated bool type. Comparisons returned an integer, and the convention was that 0 meant "false" and anything else (usually 1) meant true. It was the programmer's job to remember which things were Booleans and which were actual integers. C++ came along and (rightly) separated the two, making a special type called bool. But for compatibility with C, they left in the old trick of using integers as Booleans. Successor languages like Java would go on to remove that capability. if (myInteger) is illegal in Java and will give a compiler error.
The language checks if the condition inside the conditional is true or false. In this case, the int value gets converted into a boolean. If the size returns 0 this will get converted to false, any other value will be converted to true.
This question already has answers here:
Using the scanf() function
(4 answers)
Closed 5 years ago.
char input[256];
do{
cout<<"..."; //prompt
scanf("%s",&input5); //user inputs string
if(strcmp(input5,"block")==0)
{} //if the user types block, then it finishes the loop and goes to the cout at the bottom
else if(strcmp(input5,"attack")==0)
{
cout<<"..."<<endl;
}
else if(strcmp(input5,"look")==0)
{
cout<<"..."
}
else
{
cout<<"..."<<endl;
}
}while(strcmp(input5,"block")!=0); //loop ends when block is typed
cout<<"...";
I am having issues with my do while loop. I am doing a project for school that involves a text adventure kind of game. The user is prompting how to respond to an attack. The desired command is "block", which will move the user on to the next sequence. When "block" is typed into the scanf, it endlessly loops and prints what is in the "else" condition. I don't see what the problem is and all feedback is appreciated.
I just tried your code and it works fine (though I removed the & in the scanf), and created 'input5' as a char array.
Though that aside, there's a few things that you might want to change. I'd stick to using 'cin' instead of scanf, as you're mixing C and C++. That would allow you to use a 'string' for 'input5', and compare them using the '==' operator, which is quite a bit cleaner. Maybe think of a more descriptive name than 'input5' too, as if you've got lots of 'inputX' variables then things will get messy.
Edit: I'd also refrain from "using namespace std;", as you might end up with naming collisions.
Most likely you don't need the & operator before input5 on the scanf line, because the things scanf expects for %s fields are already pointers/arrays. Although I don't see how input5 is declared, so I'm not sure if this is the (only) problem. You should have included that in the code snippet also.
EDIT: Just a note: It's not particularly elegant to mix C-style (scanf) and C++ style (cout) IO. You wouldn't have this problem with cin.
Obviously, the loop does not terminate because the string comparison does not return equality. And this must be because input5 does not contain the typed input (and for the same reason, the else clause is executed whatever the input).
As input5 is only modified by the scanf call, this must be the root of the evil. A simple debugging session would have revealed it immediately.
The reason is simple: you must pass scanf the address of the buffer, but you are actually passing the address of the address, and overwriting the value of the variable input5 (for which we don't have the declaration but can infer char* or const char*).
In a 32 bits environment, this could cause a crash by overwriting the stack. Under 64 bits, you'll need more typing to obtain it.
I am a novice programmer and was in lecture one evening, we were studying the "if,else" coding section from my professor and I was curious about an aspect of it. What I was curious about was if we have a bunch of nested if,else's in our program, is it just bad coding style to end an if,else with an "else,if" line of code instead of if "x", else "y"? For example,
if "x"
else if "y"
else if "z"
end
compared to
if "x"
else if "y"
else "z"
end
It would still run the program without an error, but are there consequences later on other than having bad programming style?
Behind the curtain JS dont really have else if, all it is doing is generating another if statement when parsed.
e.g:
if(foo){
} else if (baz){
}
becomes
if (foo){
} else {
if (baz){
}
}
So the reason for using another else if in the end instead of else is when you want to control the else statement as-well and not just pass to that case everything else that don't fit in your first condition... (In order to control the else condition and filter it to the necessary items only)
if you do have a really long statement with a lot of else-if conditions you should consider using switch statement instead.
It all depends on what you are looking to do. The former example makes sure that all IF requirements are met. There would be instances that none of the IFs get hit in this case.
In the latter example however, ELSE "Z" would get hit for sure if all above IFs fail. This would be useful if you are assigning a variable within your IFs - your variable will definitely have a value at the end of the IF statement. If it was as in the first example, the variable will be null and might result in a null error if you try to use it later.
If there are a lot of if-thens, I would checkout the case/switch statement as well, as it is more neater to implement.
Also, remember to comment your code well - especially explaining what all the nested IFs are doing.
What is the difference between 2 if statements and 1 if-else statement?
int x;
cin >> x;
if (x==10)
cout << "Hello";
if (x!=10)
cout << "Hey";
int x;
cin >> x;
if (x==10)
cout << "Hello";
else
cout << "Hey";
In practice, the optimizer will probably make them exactly the same. The best thing to do in these cases is to try it - look at the assembly output of your compiler, and you'll see exactly what the difference is.
The difference is that in the second case the condition is checked and computed only once.
In the first example both are evaluated, always.
In the second example if first is true, it never gets to second.
The most important difference (to my mind) is that the first form is harder to read and is more error-prone.
The second form reads more like English: "If x is 10 then do this, else do that" whereas the first form essentially makes the two clauses unrelated. It's error prone because if you decide that the threshold 10 needs to change then you need to update it in two places rather than just one.
In terms of execution speed, I'd be very surprised if there is any difference at all. There will be two evaluations with the first form but that's the least of the problems. It's certainly not the sort of thing you should waste time optimising.
There is no visible output difference. However, it does make your code easier to read if you use the ladder one
if (x==10) //matches only if x is number 10 , then processor jump to next line i.e.
if (x!=10) // matches only if x is not number 10
where as
other if checked only , if the number is either 10 or anything else then 10.
In a way both will result same, but its just matter of statements.
so
in first example, both lines of if will be executed
in second example either of one is executed
So its better to use second one for performance
From a maintainability point of view the first one
violates the DRY principle.
is a lot harder to understand and modify. Not with a trivial condition, like here, but with a nice long condition you'll either have to just cut 'n paste the condition and slap a ! in front, or try to remember how De Morgan's laws were formulated... And some day that will fail, and the inverted if will fail to be the exact opposite of the first....
So, else is the way to go.
In the first block both if statement will run by the compiler...
But int the second one only 1 statement will run as both are linked with a single condition . Either if can be true or else can be true
You can understand this as considering 1st one as 'and' type
And the 2nd one as 'or' type
I have an equation with 4 variables, I am prompting the user to enter each one of these variables, and then the program decides based on what variables are entered, which variables it needs to solve for. For instance, given variable a and b, I need to solve for b and c. I am trying to come up with a way for the program to decide which variables have been entered, and which ones have not been. This is what I have been thinking so far:
int a,b,c,d;
char unknown;
cout<<"****This program decides which variables to solve for****\n;
cout<<"Please enter the known variables below, if a variable is unknown,
please enter a'?'\n"
cout<< "please enter variable a\n";
cin>>a;
cout<< "please enter variable b\n";
cin>>b;
etc....
if (a =='?'){
check b,c,d}
if (b =='?'){
check c,d}
And then running those variables through if statements to determine which variables are present and which aren't. There has to be an easier way though, these if else if statements have the potential to be ridiculous. If any of you have any advice its much appreciated. Thanks!
The pseudo-code that you've posted won't work, because >>x where xis an int will try to interpret the user's input as a specification of an integer. So, with the user typing ? what happens is that the operation fails, cin is put in a failure state, and further input operations are ignored until or if that failure state is cleared.
One way around this is to input a line at a time, into a std::string, by using std::getline from the <string> header. When you have the line of input you can then check whether it's a question mark (or simpler, just empty). And if not you can then attempt to convert the user's number specification to an int by using e.g. a std::istringstream (as I recall from the <sstream> header).
It can be instructive to make this part work even if you'll probably discover, as "Potatoswatter" commented, that the problem you're doing this for can be quite complex.
Cheers & hth.,
– Alf