Q:

Converting a phonenumber from file into a new format

I am trying to convert a series of phone number written in various ways, such as:
324.323 4345
234-345-6456.

The format I want to convert them to is: (xxx) xxx-xxxx
Here is the code i have so far, unfortunately it doesn't work..
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {

    FILE *fp;
    char str[31], ch;
    int i = 0, p1, p2, p3;
    fp = fopen("numbers.txt", "r");

        while((ch = getc(fp)) != '\n')
       {
 if(isdigit(ch))
                str[i++] = ch;
        str[i] = '\0';
        i = 0;

        sscanf(str, "%3d%3d%4d", &p1, &p2, &p3);
        printf("(%3d) %3d-%4d\n", p1, p2, p3);
      }
fclose(fp);
    return 0;
}

What am i doing wrong here? I know i probably need to isolate each integer but am having issues doing that.
Just ran it using the following: 
 404.817.6900
 (215)  686-1776
312-746-6000
877 275 5273
6173434200

and got the following:   
(  4) 4196261-32767
(  0) 4196261-32767
(  4) 4196261-32767
(  4) 4196261-32767
(  8) 4196261-32767
(  1) 4196261-32767
(  7) 4196261-32767
(  7) 4196261-32767
(  6) 4196261-32767
(  9) 4196261-32767
(  0) 4196261-32767
(  0) 4196261-32767
(  0) 4196261-32767

A:

Will this work for you?  It has three bites at the cherry, so to speak (in the worst case):
#include <stdio.h>

int main(void)
{
    char buffer[128];

    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        int p1, p2, p3;
        if (sscanf(buffer, "%*[^0-9]%3d%*[^0-9]%3d%*[^0-9]%4d", &p1, &p2, &p3) == 3 ||
            sscanf(buffer, "%3d%*[^0-9]%3d%*[^0-9]%4d", &p1, &p2, &p3) == 3 ||
            sscanf(buffer, "%3d%3d%4d", &p1, &p2, &p3) == 3)
            printf("(%3d) %3d-%4d from %s", p1, p2, p3, buffer);
        else
            printf("Failed to convert %s", buffer);
    }
    return(0);
}

For your test data set, I get:
(404) 817-6900 from  404.817.6900
(215) 686-1776 from  (215)  686-1776
(312) 746-6000 from 312-746-6000
(877) 275-5273 from 877 275 5273
(617) 343-4200 from 6173434200

