Do while loop keeps looping c++

So, I want this program to keep prompting when the number of digits isn’t 16, that part worked, but whenever I try to input 16 digits it loops without letting me type anything in again. This is what I wrote:


do{

    cout<<"insert number pls: ";
    cin>>number;
    
    //counting digits
    number_count = 0;
    while(number != 0){
        number = number/10;
        number_count++;
    }

}while(number_count != 16);


cout<<"done"<<endl;

I tried to do it with (number_count != 1) until (number_count != 10) and they worked, it only started not working from 11, why is that?

>Solution :

The value limit of int which you’re using to store your number is 2147483647 which corresponds to 10 digits that’s why it stopped working from 11. An easy workaround that is to use long long int instead the maximum value in this case is 2^63 which equals 9223372036854775807 (19 digits)
You can check the max value on a specific system programmatically with:

#include <iostream>
#include <limits>

int main() {
    std::cout << std::numeric_limits<long long int>::max();
}

Output:

9223372036854775807

However I advise that you use an array of chars to store your number instead that’s the optimal way to handle big numbers.

Leave a Reply