/*! This file is auto-generated */ .wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none} Problem 35 Write a program that inputs a te... [FREE SOLUTION] | 91Ó°ÊÓ

91Ó°ÊÓ

Write a program that inputs a telephone number as a string in the form (555) 555-5555. The program should use function strtok to extract the area code as a token, the first three digits of the phone number as a token, and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string. Both the area code and the phone number should be printed.

Short Answer

Expert verified
Use `strtok` to split the input, extract area code and phone parts, concatenate the phone parts, and print results.

Step by step solution

01

Understand the Problem

We need to write a program that breaks down a phone number in the format \((555) 555-5555\) using the `strtok` function. Our goal is to separate the area code, the first three digits, and the last four digits, and then to concatenate the first three and last four digits into one continuous string. Finally, we print both the area code and the concatenated phone number.
02

Prepare the Input

First, we will declare a string variable which holds a phone number in the format \((555) 555-5555\). This string will be processed to extract the necessary components.
03

Initialize strtok Function

Utilize the `strtok` function to split the string into tokens. The `strtok` function requires a delimiter; we will use parentheses "()", space " ", and dash "-" as delimiters to extract tokens from the phone number.
04

Extract Area Code

Call `strtok` with the input string and "()" as the delimiter to extract the area code. The first token retrieved will be "555", the area code in our input format. Store this in a variable named `area_code`.
05

Extract First Three Digits

Use `strtok` again with "-" as the delimiter to get the next part of the phone number. After the initial call to `strtok`, subsequent calls with `NULL` will continue from the last token. The first call here retrieves the three-digit part following the area code.
06

Extract Last Four Digits

Make another call to `strtok` after initializing with the last delimiter, which continues to extract the last four-digit token. Store this in a variable also.
07

Concatenate Phone Number Digits

Concatenate the first three and last four digits of the phone number using string concatenation techniques in your programming language. For example, if using C, you can use `strcat` to combine the strings.
08

Print Output

Display the extracted area code and the concatenated phone number in the required format. For instance, print "Area Code: 555, Phone Number: 5555555".

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with 91Ó°ÊÓ!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

strtok function
In C++ programming, the `strtok` function is a powerful tool used for breaking a string into a sequence of tokens or smaller strings. This function is part of the C string library, ``, and is essential for handling string manipulation tasks where separation based on delimiters is needed. The `strtok` function takes two arguments:

1. A pointer to the string that is being tokenized.
2. A string of delimiters, which can be one or more characters indicating the boundaries of each token. Examples include space " ", comma ",", dash "-", and others.

Initially, `strtok` requires the memory address of the string to begin tokenization. On subsequent calls, it uses `NULL` as the first parameter to continue from where it left off. It returns the next token or `NULL` if there are no more tokens. Here's a simple way to understand its usage:
  • Start with a string: "(555) 555-5555".
  • Use `strtok` with delimiters like "() -" to break down the parts of the phone number.
  • First token: Area code, then followed by the other parts.
This step-by-step tokenization is instrumental in parsing and extracting different segments like area code in phone numbers.
string concatenation
String concatenation is the process of joining two or more strings together into a single string. In C++, string concatenation can be efficiently handled using operators or functions. Understanding how to concatenate strings can greatly improve the way data is presented and manipulated.

In the context of our exercise, the last seven digits of a phone number must be combined into one string. Here's how string concatenation can be accomplished in C++:
  • Using the `+` operator: If you are dealing with `std::string` objects, you can concatenate using the `+` operator. For example: `std::string fullNumber = part1 + part2;`
  • Using `strcat`: In C-strings, `strcat` function is used but requires caution. Ensure the destination string is sufficiently large to hold the entire content.
This approach allows us to get the final phone number as a single entity, which is essential for processing and displaying data in many programs.
token extraction
Token extraction refers to the process of dividing a string into smaller substrings, known as tokens. This is a common task in programming when dealing with structured data formats like phone numbers, addresses, and CSV records.

In our example, token extraction is achieved through the `strtok` function, which provides a straightforward way to parse a sequence by specifying delimiters. The process involves:
  • Identifying the delimiters, such as parentheses or dashes, that separate desired tokens.
  • Applying `strtok` to isolate segments such as area code ("555"), prefix ("555"), and line number ("5555").
  • Retrieving each section individually for further processing or display.
The elegance of token extraction lies in its simplicity and its ability to reorganize and reuse sections of data without altering the original string unnecessarily.
programming exercises
Engaging with programming exercises is a highly effective way to develop problem-solving skills and enhance understanding of programming concepts such as string manipulation. By working through tasks requiring functions like `strtok` and operations like string concatenation, learners solidify their understanding.

During these exercises, key goals are to:

  • Apply theoretical knowledge to practical problems, like extracting and reformatting data.
  • Increase familiarity with C++ standard libraries, particularly those related to string handling.
  • Understand how to debug and refine solutions iteratively for better performance and accuracy.
Approaching these exercises with curiosity and persistence is crucial. Not only do they offer practice in a safe environment but they also build confidence to tackle complex real-world problems. Remember, practice is pivotal in honing skills and discovering more efficient solutions.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

For each of the following, write C++ statements that perform the specified task. Assume that unsigned integers are stored in two bytes and that the starting address of the array is at location 1002500 in memory. a. Declare an array of type unsigned int called values with five elements, and initialize the elements to the even integers from 2 to 10. Assume that the symbolic constant SIZE has been defined as 5. b. Declare a pointer vPtr that points to an object of type unsigned int. c. Use a for statement to print the elements of array values using array subscript notation. d. Write two separate statements that assign the starting address of array values to pointer variable vPtr. e. Use a for statement to print the elements of array values using pointer/offset notation. f. Use a for statement to print the elements of array values using pointer/offset notation with the array name as the pointer. g. Use a for statement to print the elements of array values by subscripting the pointer to the array. h. Refer to the fifth element of values using array subscript notation, pointer/offset notation with the array name as the pointer, pointer subscript notation and pointer/offset notation. i. What address is referenced by vPtr + 3? What value is stored at that location? j. Assuming that vPtr points to values[ 4 ], what address is referenced by vPtr -= 4? What value is stored at that location

Write two versions of each string-comparison function in Fig. 8.30. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

Perform the task specified by each of the following statements: a. Write the function header for function zero that takes a long integer array parameter bigIntegers and does not return a value. b. Write the function prototype for the function in part (a). c. Write the function header for function add1AndSum that takes an integer array parameter oneTooSmall and returns an integer. d. Write the function prototype for the function described in part (c)

(Text Analysis) The availability of computers with string-manipulation capabilities has resulted in some rather interesting approaches to analyzing the writings of great authors. Much attention has been focused on whether William Shakespeare ever lived. Some scholars believe there is substantial evidence indicating that Christopher Marlowe or other authors actually penned the masterpieces attributed to Shakespeare. Researchers have used computers to find similarities in the writings of these two authors. This exercise examines three methods for analyzing texts with a computer. Note that thousands of texts, including Shakespeare, are available online at www.gutenberg.org. a. Write a program that reads several lines of text from the keyboard and prints a table indicating the number of occurrences of each letter of the alphabet in the text. For example, the phrase To be, or not to be: that is the question: contains one "a," two "b's," no "c's," etc. b. Write a program that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, threeletter words, etc., appearing in the text. For example, the phrase Whether 'tis nobler in the mind to suffer contains the following word lengths and occurrences:c. Write a program that reads several lines of text and prints a table indicating the number of occurrences of each different word in the text. The first version of your program should include the words in the table in the same order in which they appear in the text. For example, the lines To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer contain the words "to" three times, the word "be" two times, the word "or" once, etc. A more interesting (and useful) printout should then be attempted in which the words are sorted alphabetically.

Write a program that uses function strcmp to compare two strings input by the user. The program should state whether the first string is less than, equal to or greater than the second string

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.