Adding a missing area code

Problem Statement

  • When giving their phone numbers to businesses, people with a local area code just give the last 7 digits.
  • Write a program to prompt the user for a phone number using the format 888-888-8888 where the area code is optional.
  • Print back to the user their phone number with the area code.
  • Use good coding habits

Solution

/*
Test Case 1:
Input: 888-8888 (w/o area code example)
Expected Output: 801-888-8888
Actual Output: 801-888-8888
 
Test Case 2:
Input: 541-888-8888 (w/ area code example)
Expected Output: 541-888-8888
Actual Output: 541-888-8888
 
Test Case 3:
Input: 8888888 (malformatted input)
Expected Output: 8888888 (expected malformatted output)
Actual Output: 8888888
*/
#include <iostream>
#include <string>
 
using namespace std;
 
const string LOCAL_AREA_CODE = "801-";
const int LEN_PHONE_NUM_WO_AREA = 8;
 
int main()
{
	string phone_num_user_input;
	string modified_phone_number;
	// Inputs: phone num w/ or w/o area code
	// Outputs: phone num w/ area code printed to console
 
	// Prompt user for phone num w/ w/o area code
	cout << "Gimme your phone number in 888-888-8888 format (area code optional): ";
	cin >> phone_num_user_input;
 
	// Check length of phone num
	int phone_num_len = phone_num_user_input.length();
 
	// if phone num len == 8
	if (phone_num_len == LEN_PHONE_NUM_WO_AREA)
	{
		// print modified phone num
		modified_phone_number = LOCAL_AREA_CODE + phone_num_user_input;
	}
	// otherwise
	else
	{
		// print phone num
		modified_phone_number = phone_num_user_input;
 	}
 
	// condition ? statement_if_true : statement_if_false;
	// modified_phone_number = 
                (phone_num_len == LEN_PHONE_NUM_WO_AREA ? LOCAL_AREA_CODE + phone_num_user_input : phone_num_user_input);
 
	cout << "Phone w/ area code: " << modified_phone_number << endl;
	system("pause");
	return 0;
}
cs-142/adding-a-missing-area-code.txt · Last modified: 2015/05/12 13:08 by cs142ta
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0