简体   繁体   English

为什么 strlen() 算错了?

[英]Why does strlen() counts this wrong?

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.我试图找到一种计算整数位数的方法(例如 01 有 2 位数)我认为将整数转换为字符串然后使用 strlen() 会有所帮助,但它没有。 How can I achieve my goal?我怎样才能实现我的目标?

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

When C compiler compiles your program, a lot of information present in your C source code is lost.当 C 编译器编译您的程序时,您的 C 源代码中存在的许多信息都丢失了。 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).到您的程序执行时,它不再能够判断原始 C 文件是否为上述 3 种形式中的任何一种(或任何其他等效形式)。

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));
}

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 .正如评论中所指出的, 01是一个整数文字,你已经写了... 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.让我们还将字符串中的每个字符初始化为'\\0'以避免潜在的空终止符问题,并在程序末尾打印一个漂亮的换行符。

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.它仍然打印1 ,因为这是字符串的长度,除非我们在%d说明符上使用修饰符 Let's give that field a width of 2 with %2d .让我们用%2d为该字段设置宽度为2

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

Now it prints 2 .现在它打印2

If you want to store "01" in str , you could modify it to print leading zeroes to pad the int with %02d .如果您想在str存储"01" ,您可以修改它以打印前导零以用%02d填充 int 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM