0

I have a problem with a program that should split a phone number(ex. 1231231234) that user enters into three groups and display them like this (123)-123-1234. I'm not sure how to split this number and what to use in order to complete it. I didn't completed the code party but here's what i got.

#define SIZE 3
int main(void){
        int option, j;
        int phList = 0;
        int phoneNum[SIZE];
        printf("---=== Phone Numbers ===---\n");
        while(1){
                printf("\n");
                printf("1. Display Phone List\n");
                printf("2. Add a Number\n");
                printf("0. Exit\n");
                printf("\n");
                printf("Please select from the above options: ");
                scanf("%d", &option);
                if(option == 0){
                        printf("Exiting Phone Number App. Good Bye!!!\n");
                        return 0;
                }
                if(option == 1){
                        printf("\n");
                        printf("Phone Numbers\n");
                        printf("==============\n");
                        for(j = 0; j < phList; j++){
                                printf("\n", phoneNum[j]);
                        }
                }
                if(option == 2){
                        if(phList < SIZE){
                                printf("\n");
                                printf("Add a Number\n");
                                printf("============\n");
                                scanf("%d", &phoneNum[phList]);
                                phList++;
                                } else {
                                        printf("Add a Number\n");
                                        printf("============\n");
                                        printf("ERROR!!! Phone Number List is F$
                                        }
                }
        }
return 0;
}
  • Divide by a suitable power of ten, and take the remainder of a suitable power of ten. If you have `x = 1234567890`, then `(x % 10000) == 7890`, `((x / 10000) % 1000) == 456`, and `(x / 10000000) == 123`. Other than that, I'm not sure about your approach of assuming phone numbers can be represented as integers. What happens when one wants to supply, say, the number to the University of Helsinki switchboard, +358 2 941 911? – Nominal Animal Mar 25 '17 at 19:28
  • 2
    Note that `int` is probably not large enough to store 8001234567 (ie. 8 billion+). That requires a 64 bit integer and `int` is only guaranteed to be 16 bits (though it's usually 32 these days). You need a `long long int` or `int64_t`. – Schwern Mar 25 '17 at 19:41

2 Answers2

3

I would consider using fgets() to get the phone number as a string, rather than getting it as an integer. Then you can filter the input so that only the digits are kept, allowing users to enter parenthesis, spaces, or dashes as desired. Finally, sscanf() can be used to scan the filtered string into three strings for the area code, exchange number, and subscriber number. If you like, these strings can be converted to numbers by atoi() or strtol().

The OP seems to be assuming that the phone number follows the format of the North American Numbering Plan, but phone number formats may differ. The string representation is more flexible than an integer representation, making future modifications to the code easier.

Here is an example of how this might be done:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

void filter_num(char *str);

int main(void)
{
    char buffer[1000];
    char area_code[4];
    char xch_num[4];
    char sub_num[5];

    printf("Enter phone number: ");
    if (fgets(buffer, sizeof buffer, stdin) == NULL) {
        fprintf(stderr, "Error in fgets\n");
        exit(EXIT_FAILURE);
    }

    filter_num(buffer);
    if (sscanf(buffer, "%3s%3s%4s", area_code, xch_num, sub_num) != 3) {
            fprintf(stderr, "Phone number format error\n");
            exit(EXIT_FAILURE);
        }

    printf("Phone number is: (%s) %s-%s\n",
           area_code, xch_num, sub_num);

    return 0;
}

void filter_num(char *str)
{
    char *p = str;
    while (*p != '\0') {
        if (isdigit(*p)) {
            *str++ = *p;
        }
        ++p;
    }
    *str = '\0';
}
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
  • 1
    I agree. Phone numbers aren't numbers. You can't to math on them. They're strings that happen to contain digits, and all the things you want to do with them are easier with string operations. The 11 bytes it takes to store a US number as a string isn't much worse than the 8 bytes you need to store it as a 64 bit integer (a 32 bit cannot store 800 123 4567). – Schwern Mar 25 '17 at 19:38
0

I will suggest defining a function to split the number and display that, Please have a look on this one, I have written it for you just now and works fine:

 void DisplayNum(long long int PhNum)
 {

   printf("\n ");

   for(int i=1; i<=10; ++i)   // Since Phone Number Contains 10 digits
  {
    int digit= PhNum/(pow(10,10-i));     // Spliting digits
    digit= digit%10;

    if(i==1)
     {
        printf(" (");
     }

     if(i==4)
     {
        printf(")-");
     }

     if(i==7)
    {
        printf("-");
    }

    printf("%d",digit);             // Displaying Digits
  }

 }

But make sure to use #include<math.h> at the beginning because i am using pow() function here. Then you can just pass each Phone Number in array to display to this function. The for-loop to display each Phone Number in array will be like :

 for(j = 0; j < phList; j++){
                                DisplayNum(phoneNum[j]);
                              }
HN Learner
  • 544
  • 7
  • 19
  • 1
    Note `long int` is only guaranteed to be 32 bit and may not have enough space to store 8001234567. Instead, use `long long int` or [`int64_t` from stdint.h](https://en.wikipedia.org/wiki/C_data_types#stdint.h). `pow` can also introduced floating point error. – Schwern Mar 25 '17 at 19:39
  • But in TDM-GCC pow() function works fine... There is no floating point error because there are overloads available for pow() as int pow(int, int) – HN Learner Mar 25 '17 at 19:44
  • 1
    Watch out! You're drifting into Works On My Machine™ territory. We don't know what compiler the OP is using, nor what compilers the code is targeting. Don't get too addicted to gcc extensions. :) This is on my mind because [we just had a question about `pow` and floating point error yesterday](https://stackoverflow.com/questions/42997048/pow-function-in-a-c-for-loop-rounding-down). – Schwern Mar 25 '17 at 20:13
  • Yes Sir ! I agree with you. I have also seen such errors occuring in Borland Compilers :) What I did here was not a good practice. Firstly, I thought of using a while loop to multiply 10 i times before division. But, I just wanted to keep the code short for OP. But, will take care next time ! :) – HN Learner Mar 25 '17 at 21:38