Getting an error while running following code

Use fgets to read the input string till you a reach a newline character (that means till the user hits enter). Then convert each character to int.

#include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main()
            {
            int a[100], b[100], diff=0, m=0, n=0, temp[100], s=0,z,max=0;
            int iIndex=0;
            char cString[100];
            int i=0;
            char* cpString=NULL;
            memset(&cString,0,100);
            printf("Enter binary number 1: ");
            //scanf("%s",cString);
            fgets(cString,sizeof(cString),stdin);
            cpString=cString;
            while(*cpString!='\n'){
                a[iIndex]=*cpString-'0'; // this converts char to int
                cpString++;
                iIndex++;
            }
            printf("Count of elements in a : %d\n", iIndex);
            for (i=0;i<iIndex;i++){
                printf("%d\n",a[i]);
            }
            return 0;
            }

Output:

Enter binary number 1: 1101010
Count of elements in a : 7
1
1
0
1
0
1
0

Just make sure you check wether the input number is a valid binary number!

Leave a Comment