Why doesn't strlen() return an exact value?
For example, when I input 123 it returns 2. For 12345 it returns 1. Why?
#include<stdio.h>
#include<string.h>
int main()
{
long int ui,remainder,i=0,len;
char binary[20];
scanf("%ld",&ui);
while(ui!=0) {
remainder=ui%2;
binary[i]=(char)remainder;
printf("%d ",remainder);
ui=ui/2;
i++;
}
binary[i]='\0';
printf("len is %ld\n",strlen(binary));
for(i=len-1;i>=0;i--) printf("%d",binary[i]);
return 0;
}
strlen
returns the length of an array of characters until it finds the character '\\0'
(with numeric value 0
) in it. Your binary
array is an array of characters, but you are treating them as integers as you're storing the numeric values 0
and 1
. When calculating its length, strlen
stops when it finds the first 0
you wrote.
To get the answer you need, change the binary
definition to char binary[20] = { 0 };
, save the remainder
values as ASCII characters ( binary[i] = '0' + (char)remainder;
), and print them as characters printf("%c ",binary[i]);
The reason it isn't working is because of how you're using binary
.
The strlen
function is meant to operate on NULL terminated strings. But binary
isn't treaded as a string, but as an array of bytes.
The strlen
function searches until it find a null bytes, ie a byte with a value of 0. In the case of "123", the value 0 appears after two bytes. In the case of "12345", the value 0 appears after one byte. This explains the output you're getting.
Also, you're using len
without initializing it. This leads to undefined behavior. You want to set it to i
after you exit the while
loop. You also need to change the format specifier for your first printf
from %d
to %ld
since remainder
is declared as a long int
.
There are a few problems here binary is a char so it's '0' + value print it out that way as well;
#include<stdio.h>
#include<string.h>
int main()
{
long int ui,remainder,i=0,len;
char binary[20] = {0};
scanf("%ld",&ui);
if (ui==0) { binary[i] = '0'; i++; } // Special case for zero
while(ui!=0) {
remainder=ui%2;
binary[i]=(char)remainder + '0';
printf("%d ",remainder);
ui=ui/2;
i++;
}
binary[i]='\0';
printf("len is %ld %s\n",len = strlen(binary), binary);
for(i=len-1;i>=0;i--)
printf("%c",binary[i]);
return 0;
}
For my run below I got
32
0 0 0 0 0 1 len is 6 000001
100000
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.