Error with integers with leading 0s in an if statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Error with integers with leading 0s in an if statement

#include <iostream> using namespace std; int main() { int a; cout << "Enter Password\n"; cin >> a; if (a == 910) { cout << "Access Granted\n"; } else cout << "Access Denied"; return 0; } How come I can't use a password with a leading 0? For example, I tried setting up the password to be "0910" instead of "910" but it gives me an error. Why does the leading 0 affect it?

20th Jan 2018, 5:27 PM
Ricky Velasquez
Ricky Velasquez - avatar
4 Answers
+ 3
0nnn is an octal value, but 9 is obviously *not* a valid octal digit. So 0910 is not a valid integer. Wouldn't it be much better to compare to a string anyway? You would avoid any such unwanted side-effects, and you would be able to use other alphanumerical characters in your password...
20th Jan 2018, 6:11 PM
Thomas
+ 19
Numbers starting with 0 are octal numbers and 0x hexadecimal... 010 = 8
20th Jan 2018, 5:30 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 10
I don't know why it doesn't work for you but when I input 0910, I get the string "Access Granted"
20th Jan 2018, 5:36 PM
Cool Codin
Cool Codin - avatar
0
I am talking about the part in the code when I set "a" equal to 910. if I change it to 0910, it doesn't run. I am looking up the octal and hexadecimal info now and I don't quite get it.
20th Jan 2018, 5:45 PM
Ricky Velasquez
Ricky Velasquez - avatar