I have a problem. Suppose I have
char a[50]={" 99 98 100 97 101 "};
and I want an another array of string that gives me values like this:
char b[50]={"bcdae"};
then what to do?
(ASCII value of a = 97 and so on)
I have a problem. Suppose I have
char a[50]={" 99 98 100 97 101 "};
and I want an another array of string that gives me values like this:
char b[50]={"bcdae"};
then what to do?
(ASCII value of a = 97 and so on)
#include <stdio.h>
int main() {
char a[50]={" 99 98 100 97 101 "};
char b[50]={0};
char *p = b; // p now points to b
int i, num, pos = 0;
// %d returns each number
// %n returns the number of bytes consumed up to that point
while(sscanf(a + pos, "%d%n", &num, &i)==1)
{
*p++ = (char)num; // b[0]..b[n] are set to num which is cast into a char
pos += i; // increment the position by bytes read
}
printf("%s\n", b);//cbdae
return 0;
}
The following initializations don't seem like what you meant (although they compile):
char a[50] = {" 99 98 100 97 101 "};
char b[50] = {"bcdae"};
If you meant:
char a[50] = {99, 98, 100, 97, 101};
char b[50] = "bcdae";
Then the contents of the two arrays are identical.
If you meant:
char a[50] = {99 , 98 , 100, 97, 101};
char b[50] = {'b', 'c', 'd', 'a', 'e'};
Then the contents of the two arrays are identical.
If you meant:
char a[50] = " 99 98 100 97 101 ";
char b[50] = "bcdae";
Which is equivalent to what you posted, then you can use this:
#include "string.h"
void a2b(char a[],char b[])
{
int i = 0, j;
char* pch = strtok(a," ");
while (pch != NULL)
{
b[i] = 0;
for (j=0; pch[j]!=0; j++)
{
b[i] *= 10;
b[i] += pch[j]-'0';
}
i++;
pch = strtok(NULL," ");
}
b[i] = 0;
}
Please note, however, that the above code changes the contents of the first array.
"bcdae"
is nothing else than an array of numbers: [99, 98, 100, 97, 101, 0]
. After all, there are no "letters" in the computer memory, just numbers. The last number 0
denotes the end of the string.
So, your task, seems to be a matter of repeatedly reading a number from a string (check scanf
function), and putting the read value into an array of numbers.
Hint: Learning the amount of characters you read when parsing a number may be helpful - check Get number of characters read by sscanf?