查找char数组中的元素数量

时间:2013-03-06 06:27:04

标签: arrays char size

所以即时尝试编写一个程序将二进制转换为十进制,我有一切正确的exect我没有得到正确的答案,因为我不知道如何获取数据的数量,这是我的代码

#include <stdio.h>

int a=0;

 int main ()
 {
  char  bin[20];
  int i=0, len, r=0, w;

  printf("Enter a Binary Number:  ");
  scanf("%s",bin);
  printf("\n");

 len = sizeof(bin); /*i know this is my problem how do i get len to be the size 
of the input of the user for example if the user puts 1010 len should be 4*/

  for(i = 0; i < len; i++)
     {
          r = r * 2 + (bin[i] == '1' ? 1 : 0);
       }

   printf("Decimal is: %d\n\n",r);

return 0;
 }  

1 个答案:

答案 0 :(得分:1)

在标题字符串中使用strlen函数。

#include<string>

使用strlen函数

代替sizeof(bin)
len = strlen(bin);