Home > Mobile >  Why does strlen() counts this wrong?
Why does strlen() counts this wrong?

Time:10-26

I am trying to find a way to count digits of an integer (for example for 01 there is 2 digits)I thought turning integer to string then using strlen() would help but it did not. How can I achieve my goal?

int main()
{
    int someInt = 01;
    char str[12];
    sprintf(str, "%d", someInt);
    printf("%d",strlen(str));
}

CodePudding user response:

When C compiler compiles your program, a lot of information present in your C source code is lost. Forever.

All information about how you ident your code, how you split it into multiple lines and other formatting information is lost. The names of your variables are lost. (To be precise, some of this information goes into a separate file that debuggers use when you step through your program, but that's a different topic).

Compiler produces exact same code for

int someInt = 1;

and

int someInt = 01;

and

int someInt = 001;

By the time your program executes, it can no longer tell whether the original C file was in any of the 3 forms above (or any of the other equivalent forms).

What you could do, is define your number as a string to begin with. Then convert it to an integer if you need it as an integer.

int main()
{
    char[] numericString= "01";
    int someInt;
    someInt = (int)strtol(numericString, NULL, 10);
    printf("The number is %d", someInt);
    printf("Number of digits is %d", strlen(numericString));
}

CodePudding user response:

Let's look at your code.

int main()
{
    int someInt = 01;
    char str[12];
    sprintf(str, "%d", someInt);
    printf("%d",strlen(str));
}

As noted in the comments, 01 is an integer literal and you've written... 1. Let's also initialize every character in your string to '\0' to avoid potential null terminator issues, and print a nice newline at the end of the program.

int main()
{
    int someInt = 01;
    char str[12] = {0};
    sprintf(str, "%d", someInt);
    printf("%d\n", strlen(str));
}

It still prints 1, because that's how long the string is, unless we use modifiers on the %d specifier. Let's give that field a width of 2 with -.

As suggested, in comments on this answer, the correct format specifier for printing the length of a string is %zu as the result of strlen is of type size_t rather than int.

int main()
{
    int someInt = 01;
    char str[12] = {0};
    sprintf(str, "-", someInt);
    printf("%zu\n", strlen(str));
}

Now it prints 2.

If you want to store "01" in str, you could modify it to print leading zeroes to pad the int with d.

  • Related