Trying to figure out how to output a phone number in c?

  • A+

I am trying to input a phone number and print it out in this format (888)999-1111 format but when i am trying to print it out i get some weird output that is not what i am expecting to get back out. I am printing out the values of phone both in the input and in the print function bt they are different. The one in the input function is correct but it isnt correct in the print function. Thanks in advance for the help.

int phoneInput(void) {     long int phone = 0;      printf("Input the politicians phone number with no speaces: ");     scanf("%ld", &phone);     printf("test : %ld", phone); return phone; }  int printPhone(long int phone) {     int i = 10; //the number of digits in the phone     char output[11];      printf("Test: %ld", phone);      for (i = 0; i < 10; i ++)     {     while (phone > 0)     {             output[i] = phone % 10;             phone /= 10;     }     }      printf("- Phone number: (");     i = 0;     for (i = 0; i < 3; i++)     {             printf("%d", output[i]);     }      printf(")");     i = 3;     for(i = 3; i < 6; i++)     {             printf("%d", output[i]);     }     i = 6;     printf("-");     for(i = 6; i < 10; i++)     {             printf("%d", output[i]);     }  return 0; } 


The only reason you'd need to store a value as an int, a long int, or another numeric type is if you had to do arithmetic on it (unless it's required by a homework assignment specification). Don't be fooled by the fact that a phone number is composed of numbers - it makes most sense to be stored as a string!

If you can store the phone number as a string, you should:

char *phoneInput(void) {     static char phone[100];     printf("Input the politicians phone number with no speaces: ");     fgets(phone, 100, stdin);     return phone; } 

Once you have that, it's easier to perform string manipulation on it:

printf("(%.3s)%.3s-%.4s/n", phone, phone + 3, phone + 6); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: