0

I want to convert a digit's spelling to an integer using C.For example "one" => 1,"two"=> 2 etc.I wrote the following program but it's not working.

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

    void main()
    {
      int a=0,iplen=0,j=0;
      char *num[]={"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
      char input[100],*temp;

      scanf("%s",input);
      iplen=strlen(input);

      for(int i=0;i<iplen;i++)
      {
        temp[j]=input[i];
        j++;
      }

      for(int i=0;i<10;i++)
      {
        if(temp==num[i])
        {
          a=i;
          break;
        }
      }
      printf("\n%d",a);
    }
  • why do you copy your input to another array? Anyways, this comparison is wrong: `if(temp==num[i])` ... you compare the address of `temp` to an address of one of the strings in `num`. if you want to compare strings, use [`strcmp`](https://linux.die.net/man/3/strcmp). –  Apr 04 '18 at 16:17
  • 1
    `temp` is not allocated any memory. Dereferencing it will cause undefined behaviour. Allocate memory to it first. – ameyCU Apr 04 '18 at 16:20
  • side note: `scanf("%s", ...)` is, just like `gets()`, a guaranteed buffer overflow, never use it! You might want to read my [beginners' guide away from scanf](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) –  Apr 04 '18 at 16:20
  • 1
    @ameyCU good catch ... should just be an array as well. Or shouldn't even be there in the first place, copying is just pointless here. –  Apr 04 '18 at 16:21
  • Three thing... 1. remove void before main to int, 2. assign memory to temp, 3. use strcmp() to compare two strings. – Monk Apr 04 '18 at 16:32
  • Input may contain more than one words separated by space,(I haven't implemented that in the above program though) thats why I am using temp to temporarily store an individual world and convert temp into an integer. – Mrunal Deole Apr 04 '18 at 17:58

0 Answers0