質問

Problem in C programming

I have following list:

int a[] = {0,0,1,0,0,1,0,2}

How do i convert following list items to char variable b?

Like this:

printf(%c, b) OUTPUT: 00100102

I need this for printing the values of list in embedded system lcd screen where normal print options aren't available. Couldn't find similar example from www.stackoverflow.com. Vice versa there were many solutions to convert a string into a list.

役に立ちましたか?

解決

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

int main(){
    int a[] = {0,0,1,0,0,1,0,2};
    const char *table = "0123456789";
    size_t size = sizeof(a)/sizeof(*a);
    char *b = malloc(size+1);
    int i;
    for(i=0;i<size;++i)
        b[i]=table[a[i]];
    b[i]='\0';
    printf("%s\n", b);
    free(b);
    return 0;
}

他のヒント

int a = [0,0,1,0,0,1,0,2]

That is not valid C. Perhaps you meant:

const int a[] = { 0, 0, 1, 0, 0, 1, 0, 2 };

Converting a decimal digit to a printable character in C is easy, just add '0':

printf("%c", '0' + a[0]);

will print 0.

You can iterate through the elements of your array, and printf() each one, considering it as an offset from '0':

/*

'0' + 0 = '0'
'0' + 1 = '1'
'0' + 2 = '2'

*/

const int a[] = {0,0,1,0,0,1,0,2};
const int count = sizeof(a) / sizeof(a[0]);
int i;

for (i = 0; i < count; i++) {
    printf("%c", '0' + a[i]);
}
printf("\n");

When you convert each value in an array of int to a corresponding value in an array of char, you just have an array of char. When you append the null terminator \0 (or 0) to the array of char, it becomes a C string.

int a[] = {0,0,1,0,0,1,0,2}; //use curly braces to assign values to new array.
char b[sizeof(a)/sizeof(a[0])+1];//Accomodates any size of a.  note extra space for terminating \0
int i;
//EDIT 5 following lines
b[0]=0; //ensure string is null terminated
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
    sprintf(b, "%s%d", b, a[i]);//copy one char per loop to concatenate string with all elements of `a`  
}

Now you have a string, sized according to number of array elements in a that looks like:
"00100102"
In memory you would see |48|48|49|48|48|49|48|50|0|
(the integer values of each character representation of the integers 0, 1, & 2, with the null character 0 in the last position to mark the end of string.)

Note also, the phrase sizeof(array)/sizeof(array[0]) is used to get the number of elements in an array.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top