#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12

    C : Type Conversion, int to char


    Dear fellows,

    I need help with type conversion so as to store it in a char array.

    From int to char. pls help....

    Thank you.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    If you want to convert the int to a char array, use sprintf().
    Code:
    char buf[20];
    int value = 42;
    sprintf(buf, "%d", 42);
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    thanx for your prompt reply, dude!

    I need to store it in a specific location in the array.

    I am trying to do a stricmp, if there is a match, put in the corresponding index. The program is supposed to convert Word to Number.

    eg. user input : forty five
    program returns : 45 <<<i am treating this as string.

    ones[]={"zero","one"............"nine"}
    tens[]={"ten","twenty","thrity","forty"........"ninety"}

    since forty is in tens[4], return the index and save it in s2[0].

    then five is in one[5] thus, returns the index 5 and save it in s2[1].

    finally, print s2[] while not NULL.

    i hope my description isnt too confusing :)

    ============example===========
    int x=0,i=0;
    char *s1[], *s2[]={"a","b","c"};
    ..
    ....
    for(x=0......){
    if(!(strcmp(....))
    s1[i]=x;

    }
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    Ah, so you want to convert words to numbers :). As it happens, I wrote some code to do this in PHP a while ago. See this thread: Converting english words to number

    You might want to read the thread to the end, because I posted a bugfix midway through it. Hope this helps :)
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    Originally posted by Scorpions4ever
    Ah, so you want to convert words to numbers :). As it happens, I wrote some code to do this in PHP a while ago. See this thread: Converting english words to number

    You might want to read the thread to the end, because I posted a bugfix midway through it. Hope this helps :)

    Cheers, mate!

    I will go read it now.......

    besides the solution u are offering, will u be offerring friendship too?

    I am very moved by your kindness. It means a lot to me.

    My assignment is actually due 10hrs ago. My project mate decided to give up so i had to work alone....anyhow, i should quit complaining :P

    BIG THANK YOU!
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    I am sorry, i cant quite comprehend it in PHP.

    could u pls help me with converting int to char?

    initially, i tried
    int i,x;
    char *s1[];
    for(i=0;....)
    s1[x]=i; <<<this fails, what should i do instead?

    but it fails, segmentation fault, due to different variable type.....
  12. #7
  13. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    char *s1[]; is uninitialized, so you can't assign to it. That's why you're getting a segmentation error :). Normally, I try to avoid doing homework, but since I was bored, here's a C translation of my PHP code.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define FORUMS_DEVSHED_COM 1
    #define MAX_ARRAY 20
    #define MAX_BUF   80
    
    int valuearray[MAX_ARRAY];
    int arrayindex = 0;
    
    void init_array(void) {
      register int i;
      for (i = 0; i < MAX_ARRAY; i++) 
        valuearray[i] = 0;
      arrayindex = 0;
    }
    
    int main(void) {
      char buf[MAX_BUF];
    
      printf("Enter a number: ");
      fgets(buf, MAX_BUF, stdin);
    
      init_array();
      printf("The value is %d\n", words_to_number(buf));
    
      return 0;
    }
    
    void push_array(int value) {
      valuearray[arrayindex] = value;
      if (++arrayindex >= MAX_ARRAY) {
        fprintf(stderr, "ERROR: Stack depth exceeded. Exiting...\n");
        exit(1);
      }
    }
    
    int pop_array(void) {
      if (--arrayindex < 0) 
        arrayindex = 0;
      return valuearray[arrayindex];
    }
    
    int peek_array(void) {
      if (arrayindex == 0) 
        return valuearray[0];
      else 
        return valuearray[arrayindex - 1];
    }
    
    int check_adds(char *word, int *val) {
      char *words[] = {
        "zero", "one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine", "and",
        "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
        "thirty", "forty", "fifty", "sixty", "seventy",
        "eighty", "ninety", "END"
      };
      int values[] = { 0, 1, 2, 3, 4, 5,
                        6, 7, 8, 9, 0,
                        11, 12, 13, 14, 15,
                        16, 17, 18, 19, 20,
                        30, 40, 50, 60, 70,
                        80, 90, 0 };
    
      register int i;
    
      for (i = 0; strcmp(words[i], "END") != 0; i++) {
        if (strcasecmp(word, words[i]) == 0) {
          *val = values[i];
          return 1;
        }
      }
    
      return 0;
    }
    
    int check_muls(char *word, int *val) {
      char *words[] = {
        "hundred", "thousand", "million", "billion", "END"
      };
      int values[] = {
        100, 1000, 1000000, 100000000, 0
      };
      register int i;
    
      for (i = 0; strcmp(words[i], "END") != 0; i++) {
        if (strcasecmp(word, words[i]) == 0) {
          *val = values[i];
          return 1;
        }
      }
      
      return 0;
    }
    
    int words_to_number(char *words) {
      char buf[MAX_BUF + 2];
      char *word;
      int value = 0, result = 0;
      register int i;
    
      buf[MAX_BUF + 1] = '\0';
      strncpy(buf, words, MAX_BUF);
    
      for (word = strtok(buf, " \n,"); word; word = strtok(NULL, " \n,")) {
        if (check_adds(word, &result)) 
          value += result;
        else if (check_muls(word, &result)) {
          if (value != 0) {
            if (peek_array() > value * result) 
              value *= result;
            else 
              value = (pop_array() + value) * result;
          } else {
            value = pop_array();
            value *= result;
          }
          push_array(value);
          value = 0;
        }
        else {
          fprintf(stderr, "Unrecognised word: %s\n", word);
          exit(2);
        }
      }
      push_array(value);
    
      /* Now compute the sum of the values in the value_array */
      value = 0;
      for (i = 0; i < arrayindex; i++) 
        value += valuearray[i];
    
      return value;
    }
    Last edited by Scorpions4ever; September 12th, 2003 at 03:57 PM.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  14. #8
  15. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    I tested the program with inputs such as:
    Forty seven
    Four hundred and thirty eight
    Six million, fifty two thousand, three hundred and seventy two
    Six million, seven hundred and fifty two thousand, seven hundred and twenty two
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    thanx dude....it works fine!

    thank you for your kindness :)
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Location
    Flint, MI
    Posts
    328
    Rep Power
    12
    The code to convert a number to a single character representation is:

    Code:
    int num;
    char a;
    
    a = '0' + (num % 10);
    Clay Dowling
    Lazarus Notes
    Articles and commentary on web development
    http://www.lazarusid.com/notes/
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    Originally posted by ClayDowling
    The code to convert a number to a single character representation is:

    Code:
    int num;
    char a;
    
    a = '0' + (num % 10);
    That's using ASCII, right?

    I am using the code provided Scorpions4ever as a good reference guide for my assignment. It has opened my eyes to another good possibility and a better understanding of the alogarithm.

    Still, I have a little difficulty as my foundation is shaky.

    My lack of understanding is as follows, pls kindly guide me...

    I am trying do a strcasecmp with the user input versus the contents in array.

    If matched, store the index as a string.

    I am treating all output as string.

    Eg. If user key in ten thousand. Ten will return 10 while thousand will return 3 0's.


    ======part of my code that has problem==========

    int i;
    char buffer[256], output[12];
    char *ones[]={"zero", "one", "two",....."nine"};

    char *token=strtok(buffer, " /t");

    while(token){
    for(i=0;i<strlen(ones)-1;i++)
    if(!(strcasecmp(token,ones[i]){ /*debugger shows this line causes "Segmentation Fault"
    output[x]='0' + (i%10);
    x++; /*moves index of output array forward*/
    } /*end if*/
    strtok(NULL, " /t");
    } /*end while*/

    ========end of part of code=========
    Last edited by poppers; September 15th, 2003 at 03:47 PM.
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Location
    Flint, MI
    Posts
    328
    Rep Power
    12
    The proper way to traverse an array of strings is a little different than what you're doing. First, you need to build the array with a tailing NULL. Then test for that null to find when you have reached the end. So:

    Code:
    char* ones[11] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", NULL};
    int i;
    
    for(i=0; ones[i]; i++) 
      if (strcmp(ones, input) == 0) 
        output[place] = '0' + i;
    Clay Dowling
    Lazarus Notes
    Articles and commentary on web development
    http://www.lazarusid.com/notes/
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    still, there is segmentation fault despite the changes....
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    31
    Rep Power
    12
    /*This program converts positive numerical input to word and positive word to numeral */
    #include<stdio.h>
    #include<string.h>



    int main(){
    char buffer[256], output[13];
    int number=0,i=0,x=0,flag=0,thousand=0,hundred=0,ten=0;

    char *number_name[]={"zero","one","two","three","four","five","six","seven","eight",
    "nine","ten","eleven","twelve","thirteen","fourteen","fifteen",
    "sixteen","seventeen","eighteen","nineteen","twenty",NULL};
    char *one_name[]={"zero","one","two","three","four","five","six","seven",
    "eight","nine",NULL};
    char *teens_name[]={"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
    "seventeen","eighteen","nineteen",NULL};
    char *ten_name[]={"","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety",NULL};


    while(fgets(buffer,256,stdin)){
    if(buffer[0]>='0' && buffer[0]<='9') /*Check if first element of input is integer*/
    {
    sscanf(buffer,"%d",&number);
    if(number==0)
    fputs(number_name[number],stdout);
    while(number!=0)
    {
    if((number>=1000 && (number%1000)>-1) && ((number/1000)<21))
    { thousand = number/1000;
    printf("%s thousand ",number_name[thousand]);
    number = number%1000;
    }

    else if((number >=100 && (number%100)>-1) && ((number/100)<10))
    { hundred = number/100;
    printf("%s hundred ",number_name[hundred]);
    number = number%100;
    }

    else if((number >=10 && (number%10)>-1) && ((number/10)<10))
    { ten = number/10;
    if(ten>1 && ten<10)
    printf("%s ",ten_name[ten]);
    else if(ten==1 && (number%10)==0)
    printf("%s",number_name[number]);
    number = number%10;
    }
    else
    { number = number%10;
    if(ten==1)
    printf("%s",number_name[number+10]);
    else
    printf("%s",number_name[number]);
    number = 0;
    }
    } /*end while(number!=0)*/
    } /*end if(buffer....)*/


    else if(((buffer[0]>='A') && (buffer[0]<='Z')) || ((buffer[0]>='a') && (buffer[0]<='z'))) /*check if first element of input is char*/
    {
    char *token = strtok(buffer," \t");

    while(token)
    {
    for(i=0;i<11;i++)
    {
    if(!strcasecmp(one_name[i],token)) /*debugger reported that program terminates here & cause segmentation fault*/
    {
    flag=1;
    output[x]='0' + i;
    x++;
    break;

    }
    else if(!strcasecmp(token,ten_name[i]))
    { flag=1;
    output[x-1]='0' i;
    x+=2;
    break;
    }

    else if(!strcasecmp(token,teens_name[i]))
    { flag=1;
    output[x]='0'+ i;
    output[x-1]='1';
    x+=2;
    break;
    }

    else if(!strcasecmp(token,"hundred"))
    { flag=1;
    output[x]='0';
    output[x+1]='0';
    x+=2;
    break;
    }

    else if(!strcasecmp(token,"thousand"))
    { flag=1;
    output[x]='0';
    output[x+1]='0';
    output[x+2]='0'
    x+=3;
    break;
    }
    token = strtok(NULL, " \t");

    } /*end for*/
    if(x==0)
    output[x+1]='\0';
    else
    output[x]='\0';
    } /*end while(token)*/


    if(flag==1)
    {
    for(i=0;output[i]!='\0';i++)
    printf("%d",output[i]);
    }
    else
    fputs("Invalid inputs!",stdout);

    } /*end if(buffer...)*/

    else
    fputs("Invalid inputs!",stdout);

    fputs("\n",stdout);

    } /*end while(fgets....)*/
    return 0;

    } /*end main()*/



    It can compile but cant run properly. Hope someone will point out the mistakes I have made here.

IMN logo majestic logo threadwatch logo seochat tools logo