RithvikK
RithvikK

Reputation: 111

Why can`t I put a zero in front of an integer in an "if" statement

Why does my little cheat code not work when I put the zero in front of it. When I take the zero out and put the little cheat code in it works just fine. However, when I put the zero in and use the cheat code - it will skip right over.

#include <iostream>
#include <random>

int main() {
    bool correct = false;
    std::cout << "Put a Number from 1 to 100" << std::endl;
    int guess = 0;
    std::cin >> guess;
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> rnd(0, 101);
    int answer = rnd(mt); //random number
    while (correct == false)
    {
        if (guess == answer)
        {
            std::cout<<"You got it!!!"<<std::endl;
            correct = true;
        }
        else if (guess == 01010101)#<--------------------Problem
        #it works when it is 1010101
        {
            std::cout<< answer<< std::endl;
            std::cout << "Put a Number from 1 to 100" << std::endl;
            std::cin >> guess;
        }
        else if (guess > answer)
        {
            std::cout<<"Your guess is to high guess again"<< std::endl;
            std::cout << "Put a Number from 1 to 100" << std::endl;
            std::cin >> guess;
        }
        else if (guess < answer)
        {
            std::cout<<"Your guess is to low guess again"<< std::endl;
            std::cout << "Put a Number from 1 to 100" << std::endl;
            std::cin >> guess;
        }

        else
        {
            std::cout << "Put a Number from 1 to 100" << std::endl;
            std::cin >> guess;
        }


    }
}

Upvotes: 2

Views: 142

Answers (1)

cdhowie
cdhowie

Reputation: 169068

A leading zero on a numeric literal indicates that the literal is expressed in octal (base 8) notation1, which (obviously) has a different magnitude than the same digits interpreted as decimal (base 10).

The octal number 01010101 is equal to the decimal number 266305.


1 Unless the leading zero is followed by an x, then it's interpreted as hexadecimal (base 16).

Upvotes: 14

Related Questions