204k views
5 votes
Write a program in C that does the following:

Asks the user to enter a phone number using the format (xxx) xxx-xxxx. Displays the phone number entered by the user in the format xxx.xxx.xxxx Determines whether the number is a Charlotte number (704) and displays a message to indicate this. Include logic to display an error if the user does not enter the number in the correct format.
Sample Output:
Enter a telephone number using the format (xxx) xxx-xxxx
(704) 586-7071
You entered: 704.586.7071
This is a Charlotte phone number.

User Raj Dhakad
by
6.9k points

1 Answer

3 votes

Answer:

#include <stdio.h>

#include <string.h>

int main() {

char phoneNumber[15];

printf("Enter a telephone number using the format (xxx) xxx-xxxx\\");

scanf("%s", phoneNumber);

int len = strlen(phoneNumber);

if (len != 14 || phoneNumber[0] != '(' || phoneNumber[4] != ')' || phoneNumber[5] != ' ' || phoneNumber[9] != '-') {

printf("Error: Incorrect phone number format\\");

return 0;

}

printf("You entered: %c%c%c.%c%c%c.%c%c%c%c\\", phoneNumber[1], phoneNumber[2], phoneNumber[3], phoneNumber[6], phoneNumber[7], phoneNumber[8], phoneNumber[10], phoneNumber[11], phoneNumber[12], phoneNumber[13]);

char areaCode[4];

strncpy(areaCode, &phoneNumber[1], 3);

areaCode[3] = '\0';

if (strcmp(areaCode, "704") == 0) {

printf("This is a Charlotte phone number.\\");

} else {

printf("This is not a Charlotte phone number.\\");

}

return 0;

}

Step-by-step explanation:

  1. First, the program asks the user to enter a phone number using the format (xxx) xxx-xxxx.
  2. Then, the program uses scanf to store the phone number entered by the user in the phoneNumber array.
  3. Next, the program uses the strlen function to get the length of the phone number string and checks if it's equal to 14. If not, it displays an error message and returns 0.
  4. The program then uses the printf function to display the phone number in the format xxx.xxx.xxxx.
  5. The program creates a areaCode array to store the first three characters of the phone number, which is the area code.
  6. Finally, the program uses the strcmp function to compare the areaCode with "704". If they're equal, it displays a message indicating that this is a Charlotte phone number. If not, it displays a message indicating that this is not a Charlotte phone number.
User Hasan Hasanov
by
7.0k points