# Thread: Convert Phone Letters To Numbers

1. ## Convert Phone Letters To Numbers

iI am a new C programmer and I am trying to write a program that will convert the letters of a phone number such as 1-800-collect into the correct numbers. Could someone help me get this started. I'm not too sure how to turn my getchar() into a number.

2. you could check to see first what letter the first character is for example A,B, and C are all 2 so if the first character is A,B, or C, input a 2 into a seperate int variable, and for teh second letter you would do the same thing, etc

ABC=2
DEF=3
GHI=4
JKL=5
MNO=6
PRS=7
TUV=8
WXY=9

3. The function strchr() scans a string for the first occurrence of a given character; strchr() returns a pointer to the first occurrence of the character c in s; if c does not occur in s, strchr returns null. This could be used for something like the following.

Code:
```#include <stdio.h>
#include <string.h>

char Digit(char ptr)
{
if(strchr("ABCabc", ptr))        return('2');
else if(strchr("DEFdef", ptr))   return('3');
else if(strchr("GHIghi", ptr))   return('4');
else if(strchr("JKLjkl", ptr))   return('5');
else if(strchr("MNOmno", ptr))   return('6');
else if(strchr("PQRSpqrs", ptr)) return('7');
else if(strchr("TUVtuv", ptr))   return('8');
else if(strchr("WXYZwxyz", ptr)) return('9');
return(ptr);
}

int main(void)
{
const char number[] = "1-800-COLLECT", *ptr;
puts(number);
for(ptr = number; *ptr; ++ptr)
{
putchar(Digit(*ptr));
}
return(0);
}

/* my output
1-800-COLLECT
1-800-2655328
*/```
Another way might be as follows.
Code:
```#include <stdio.h>
#include <string.h>

char Digit(char ptr)
{
const char *Letter[] =
{
/* 2 */"ABCabc",
/* 3 */"DEFdef",
/* 4 */"GHIghi",
/* 5 */"JKLjkl",
/* 6 */"MNOmno",
/* 7 */"PQRSpqrs",
/* 8 */"TUVtuv",
/* 9 */"WXYZwxyz",
};
size_t i;
for(i = 0; i < sizeof(Letter)/sizeof(*Letter); ++i)
{
if(strchr(Letter[i], ptr))
return(i + '2');
}
return(ptr);
}

int main(void)
{
const char number[] = "1-800-COLLECT", *ptr;
puts(number);
for(ptr = number; *ptr; ++ptr)
{
putchar(Digit(*ptr));
}
return(0);
}

/* my output
1-800-COLLECT
1-800-2655328
*/```

4. This is the code that I have come up with so far. Can anyone help me out as to why it is not converting my getchar() statement into a letter

Code:
```#include <stdio.h>

main(){

char ch;
int i;

printf ("Enter a phone number: ");
while ((ch = getchar()) != '\n');

i = ch;

if ('a' <= ch && ch <= 'c')
i = 2;
if ('d' <= ch && ch <= 'f')
i = 3;
if ('g' <= ch && ch <= 'i')
i = 4;
if ('j' <= ch && ch <= 'l')
i = 5;
if ('m' <= ch && ch <= 'o')
i = 6;
if ('p' <= ch && ch <= 's')
i = 7;
if ('t' <= ch && ch <= 'v')
i = 8;
if ('w' <= ch && ch <= 'y')
i = 9;

printf ("%d", i);

return 0;
}```
&#91;code]&#91;/code]tagged by Salem

5. Thanks for your help Salem!