Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading