1

I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.

Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.

Can I get the user's input as a string and then use string.length and convert it to an array of digits?

#include <iostream>

using namespace std;

int main()
{
    int N;
    cin >> N;
    while(N--)
    {
        int num;
        cin >> num;

        int arr[1000];
        for (int i=0 ;i<???;i++)
        {
            arr.[i]=num%10;
            num = num /10;
        }

    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
logan_92
  • 117
  • 9
  • Note: i can't take the number of elements in num from user – logan_92 Jul 09 '20 at 23:10
  • 1
    Just as a side note: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/12149471) – Andreas Wenzel Jul 09 '20 at 23:14
  • thank you Andreas for this note :) – logan_92 Jul 09 '20 at 23:39
  • Just a meta-comment: you've gotten answers explaining how to do this. But keep in mind that an **integer** does not have digits. All it has is a value. Its **text representation** has digits. So the question here could have been "if I have an integer value, how many digits will I end up with if I convert it to text?". On the other hand, as the answers have pointed out, if the input is text, all you need to do is count the characters. Converting those characters to an integer value adds nothing to the solution. – Pete Becker Jul 10 '20 at 12:23

3 Answers3

3

an easier way to do this is to convert it to a string then count the length of said string

#include <iostream>
#include <string>

using namespace std;  
int main()  {  
    int n;
    cin >> n;

    string str = to_string(n);
    cout <<"the length of" <<str << "is:" <<str.length() <<"\n";  
}  

typing in a 41 will print out.

the length of 41 is 2

  • Oh yeah, I forgot about `std::to_string()` – Remy Lebeau Jul 09 '20 at 23:26
  • thank you for your answer , sorry for that but what to_string actually does internally ?? and do you recommend to use those ready methods at the beginning of my learning of programming ?? – logan_92 Jul 09 '20 at 23:33
  • @logan_92 "*what to_string actually does internally ??*" - does it really matter? That is an implementation detail. It can convert the integer to a string however it wants to, using whatever techniques it wants. What is important is that it works. – Remy Lebeau Jul 09 '20 at 23:37
  • i don't know , i'm trying to learn programming so i try to know how those things work if i want to do some methods or functions for myself. i don't know if this approach of learning programming is correct or not. – logan_92 Jul 09 '20 at 23:40
  • 1
    @logan_92 I recommend this approach. Learn and use all the available tools at your disposal. Then when you actually need to implement something that's not available, you can look at how the tools (that you know how to use) work under the hood, and then adapt that. – cigien Jul 09 '20 at 23:51
  • @cigien thank you for your answer :) i will follow your advice. – logan_92 Jul 10 '20 at 00:15
2
        while (num != 0)
        {
            arr.[i]=num%10;
            num = num /10;
        }

is a common pattern that's close to what you already have.

Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.

Kevin Wang
  • 2,673
  • 2
  • 10
  • 18
  • thank you for the answer but i think in this solution i can't define the size of array at the beginning because i still didn't get the size of num till i do this loop. i will assume a large size of elements so i will stick with your 2nd recommendation to use string to initialize the array size at the beginning – logan_92 Jul 09 '20 at 23:30
  • 1
    "*i can't define the size of array at the beginning*" - yes, you can, because integers have a max number of digits - 3 digits for an 8-bit int, 5 digits for a 16-bit int, 10 digits for a 32-bit int, and 19 digits for a 64-bit int. So, you don't really need to allocate the array larger than the max for the type of integer you are working with. – Remy Lebeau Jul 09 '20 at 23:39
  • thank you for your reply , sure integer has 4 bytes as size , but i think if i reserve this size at the beginning this will be a waste of memory. sorry if my answer is not correct i'm still learning. – logan_92 Jul 09 '20 at 23:44
  • 1
    @logan_92 You are confusing bytes with digits. They are not the same thing. You are trying to produce an array of digits, not an array of bytes. An integer's byte size will always be smaller than its max digit count: 8 bits = 1 byte = 3 digits max (255), 16 bits = 2 bytes = 5 digits max (65535), 32 bits = 4 bytes = 10 digits max (4294967295), and 64 bits = 8 bytes = 19 digits max (9223372036854775807). In your example, `123456` is 6 digits, and uses 17 bits, so it requires a 32-bit or larger int. – Remy Lebeau Jul 10 '20 at 00:00
  • 1
    32 bits = 2 to the 32'nd power = 4294967295 max for an unsigned int32. For a signed int32, (2 to the 31'st power) - 1 = 2147483647 max – Remy Lebeau Jul 10 '20 at 00:03
  • but what is the relation between digit and bit??? it looks like multiplied by 2.5?? – logan_92 Jul 10 '20 at 00:04
  • 1
    @logan_92 In computers, integers are represented as powers of 2. The number of bits represents the highest power that 2 can be raised to. – Remy Lebeau Jul 10 '20 at 00:05
  • ok i got it , you do 2 power 16 and calculate how many digit that will represent – logan_92 Jul 10 '20 at 00:07
  • 1
    @logan_92 2 to the 16'th power, minus 1, is 65535, the highest 16bit integer. Don't forget the minus 1, that is important, because the the way integers handle zero and negatives. If you want to know more, there are books on this subject. – Remy Lebeau Jul 10 '20 at 00:09
  • 1
    remy , thank you so much :) , you are so helpful ,God Bless you – logan_92 Jul 10 '20 at 00:09
1

Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:

#include <iostream>
#include <string>

int main()
{
    std::string S;
    std::cin >> S;

    int arr[1000] = {};
    for (size_t i = 0; i < S.size(); ++i)
    {
        arr[i] = (S[i] - '0');
    }

    return 0;
}

Alternatively:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string S;
    std::cin >> S;

    int arr[1000] = {};
    std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });

    return 0;
}

Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.

Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:

#include <iostream>
#include <string>

int main()
{
    unsigned int N;
    std::cin >> N;

    std::string S = std::to_string(N);

    int arr[1000] = {};
    for (size_t i = 0; i < S.size(); ++i)
    {
        arr[i] = (S[i] - '0');
    }

    // or:
    // std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });

    return 0;
}

Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:

#include <iostream>

int main()
{
    unsigned int N;
    std::cin >> N;

    int arr[1000] = {};
    size_t i = 0;

    while (N != 0)
    {
        arr[i++] = num % 10;
        num /= 10;
    }

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Remy , i really appreciate your hard work to answer my question , thank you for that.i'm just trying to understand that line arr[i] = (S[i] - '0'); , what it does , does it convert string to number?? – logan_92 Jul 09 '20 at 23:37
  • 1
    @logan_92: Take a look at the [ASCII table](http://www.asciitable.com/). It subtracts `'0'` (which evaluates to the number 48) from the character's ASCII code. This effectively converts a character's ASCII code to the digit's value. For example, the digit `'8'` has the ASCII code 56. If you subtract `'0'` (=48) from it, you get the number 8. – Andreas Wenzel Jul 09 '20 at 23:43
  • 1
    @logan_92 not a whole *string*, no, but an individual character, yes. `char` is an integral type, like `int`, so a `char` can have arithmetic applied to it. Subtracting char `'0'` (numeric value 48) from char `'0'` returns an integer `48-48=0`. Subtracting `'0'` from `'1'` (numeric value 49) returns an integer `49-48=1`. And so on, up to `'9'` (numeric value 57), returning an integer `57-48=9`. This is a quick and simply way to convert chars `'0'..'9'` into integers `0..9` – Remy Lebeau Jul 09 '20 at 23:50
  • thank you for your answers , my last question => if i assume array[1000] but i don't need this size all the time , is this flaw in optimization of my code?? – logan_92 Jul 09 '20 at 23:51
  • 1
    @logan_92 See [my comment](https://stackoverflow.com/questions/62825026/how-to-know-the-number-of-digits-in-an-integer/62825084#comment111099149_62825084) on [Kevin Wang's answer](https://stackoverflow.com/a/62825084/65863) about that. – Remy Lebeau Jul 09 '20 at 23:52