Feb 11, 2016 at 8:18am UTC
Hello, I'm experimenting with if statements and have encountered something I don't understand.
I don't understand why the program doesn't execute else when I enter a character or string; instead it executes the else if.
for example:
when I input 'a'
the program spits back you did not enter -1 or -2.
Is this because the program doesn't read the character or string because I've defined an integer?
Also, why does it choose to execute else if rather than if or else when the condition is stated?
I would expect it to go straight to else since a character is neither > or < 0.
Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number" ;
cin >> num;
if (num > 0)
{
for (num; num == 1 || num == 2;)
{
cout << "you pressed 1 or 2\n" ;
return 1;
}
cout << "you did not press 1 or 2\n" ;
}
else if (num < 0)
{
for (num; num == -1 || num == -2;)
{
cout << "you pressed -1 or -2" ;
return 1;
}
cout << "you did not press -1 or -2" ;
}
else
{
cout << "you entered 0 or a character\n" ;
}
return 0;
}
** edit
Also, I tried to assign a string to
num instead of inputting a number.
This now executes the if statement and responds
"you did not press 1 or 2"
Last edited on Feb 11, 2016 at 8:25am UTC
Feb 11, 2016 at 8:48am UTC
Last edited on Feb 11, 2016 at 9:02am UTC
Feb 11, 2016 at 9:02am UTC
Did you try using the "edit and run" button on your original post? I'm lazy and did not try creating a project. Set a breakpoint at line 8, then step forward (over). You should be able to see what value num is holding than.
A character and a string are two different things. A string is an array of characters, even it is only one character. C++ will use the the ASCII value of a char, if it is expecting an int. It will also do the opposite if expecting a char.
Last edited on Feb 11, 2016 at 9:03am UTC
Feb 11, 2016 at 9:23am UTC
I'm not sure what this means
Set a breakpoint at line 8, then step forward (over).
but I found that when I type in a letter or words
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number" ;
cin >> num;
cout << num;
return 0;
}
and print out
num I get
which i find really interesting and explains why I keep getting
you did not enter -1 or -2
I guess this points to what coder777 said about not being able to predict the value?
So, is there a reason characters and strings are holding this value in my program?
Thanks for everyone's help! Sorry if these are weird questions, I'm just starting out.
Last edited on Feb 11, 2016 at 9:45am UTC
Feb 11, 2016 at 9:30am UTC
He is exactly right, I probably just got lucky.