Domanda

I'm having a problem to turn ascii code in a vector to a string... example...

main(){
    //Having 'abcdefhgijkl', the position 0 is 'l'.
    int x[3] ={0};
    x[2] = ('a'<<24) + ('b'<<16) + ('c'<<8) + 'd';
    x[1] = ('e'<<24) + ('f'<<16) + ('g'<<8) + 'h';
    x[0] = ('i'<<24) + ('j'<<16) + ('k'<<8) + 'l';

    int i = 0;
    char buf[12];

    while(i < sizeof(x)){
        sprintf(buf,"%d",x[i]);
        printf("%s \n", buf);
        i++;
    }
}

My intention is to print 'abcdefghijkl' but the output is numbers... I have done many search but nothing seems to work, i tried fucntion itoa, snprintf and now sprintf and nothing seems to work.

È stato utile?

Soluzione

Here are some improvements to your program:

  • To do what you are trying to do with the sprintf call you must use %s to read it as a string, and not %d which will just give you numbers. Since these "strings" are not real nul-terminated strings, you must limit the length of the string to 4 bytes with %.4s.

  • The array x has three elements, but sizeof(x) returns the size in bytes which is 12 (usually). So in order to iterate three times you need to calculate total size divided by the size of one element. That will give you number of elements (a common way to do this in a general way it to #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])).

  • The buf variable is too small, you need to increase by one to have room for the 12 characters + one byte for the nul termination character \0.

  • If you want "abcdefghijkl" as output you need either to reverse the order of x initialization or you need to reverse the loop to start with the highest number and run down to zero. And even then you run into endianess issues.

  • The loop can preferably be converted to a for loop.

  • The main function ought to have a proper signature.

Testing with

#include <stdio.h>

int main(int argc, char *argv[]){
    int x[3] ={0};
    x[0] = ('a'<<24) + ('b'<<16) + ('c'<<8) + 'd';
    x[1] = ('e'<<24) + ('f'<<16) + ('g'<<8) + 'h';
    x[2] = ('i'<<24) + ('j'<<16) + ('k'<<8) + 'l';

    int i;
    char buf[12 + 1];

    for (i = 0; i < sizeof(x)/sizeof(int); i++){
        sprintf(buf,"%.4s", (char *)&x[i]);
        printf("%s \n", buf);
    }
    return 0;
}

it gives the following output:

dcba
hgfe
lkji

Altri suggerimenti

The below modified program will output "abcdefghijkl"

#include <stdio.h>

main()
{

   //Having 'abcdefhgijkl', the position 0 is 'l'.
   int x[3] ={0};
   int n = 0;
   x[2] = ('a'<<24) + ('b'<<16) + ('c'<<8) + 'd';
   x[1] = ('e'<<24) + ('f'<<16) + ('g'<<8) + 'h';
   x[0] = ('i'<<24) + ('j'<<16) + ('k'<<8) + 'l';

   int i = 0;
   char buf[12+1] = {'\0'};
   char *ptr = (char*)x + sizeof(x)-1;


   while(i < sizeof(x)){
      sprintf(((char*)buf+i),"%c",*ptr);
      i++;
      ptr--; 
   } 

   printf("The string is = %s\n",buf);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top