Question

I need help with this assignment in C++, please!

*** The instructions and programming style details are crucial for this assignment!

Goal: Your assignment is to write a C+ program to read in a list of phone call records from a file, and output them in a moreTo limit the scope of this assignment we will only consider E.164 phone numbers from the following regions CC Region 1 NorthMain Program Here is an example what it should look like when your main program is run on the file above File Name phoneLog1.Functions to write: You are to write the following seven functions for vour main program to call Function Name What does theFormatting | get Local Phone | Takes one string parameter (phone number) * Returns a formatted local phone number string CounError Handling Your main program should handle incorrectly formatted data field gracefully Consider the following input file// Title: Lab 1 - PhoneCalls.cpp // Purpose: read in a list of phone call records from a file, and output them /I in a more uYou should adopt a consistent style for how you format your curly braces 3. Do it the same way throughout your file. Make sur

Goal: Your assignment is to write a C+ program to read in a list of phone call records from a file, and output them in a more user-friendly format to the standard output (cout). In so doing, you will practice using the ifstream class, I'O manipulators, and the string class. File format: Here is an example of a file containing three phone call records: phoneLog1.txt - Notepad File Edit Format View Help 110054 +12062812000 5912 091233 +33140205990 364 145316 +85223677065 180 Each line records one phone call. As you can see, each line contains 3 different fields: start, E.164, and duration Here is an explanation of these three fields:
To limit the scope of this assignment we will only consider E.164 phone numbers from the following regions CC Region 1 North America (US, Canada, and some Caribbean islands) 33 France 852 Hong Kong SAR We've picked these regions because they have simple 12-digit E.164 formats. Duration: This field consists of a variable number of digits, specifying the number of seconds the cal lasted In this assignment you can assume that a phone log file contains at least one line. In addition, you may assume that each line has exactly three fields and is terminated by an end of line. It is possible that some fields are not formatted correctly. Your program should not crash because a field is incorrectly formatted.
Main Program Here is an example what it should look like when your main program is run on the file above File Name phoneLog1.txt Τι me 11:00:54 NA 09:12:33 FR 14:53:16 HK Country Phone Number Durati on (206)-281-2000 98:32 01 40 20 59 90 6:04 2367 7065 3:00 1. The main program first prompts the user to enter a file name, with the following message a. "File Name:" (Case Sensitive) You will open that file for input. 2. a. If the file is not successfully opened, you will print an error message "Failed to open file", followed by std: :endl, (Case Sensitive) and exit the main program. 3. Print the four column headers, like the following (be careful for spaces and cases Duration Phlonle Nlulmlble r 1 mle Begin the iterative process of reading the three fields on a line 4. The three fields should be read into string variables Then validated before formatting to be outputted in columns as shown above a. b. Your main program should output the same file name prompt, and same column titles as shown in the screenshot. You should also use the exact same field widths. The time field is width 8 (followed by 2 blank spaces), the country field is width 2 (followed by 7 blank spaces), and the phone number field is width 14 (followed by 2 blank spaces). Make sure you zero fill the seconds field of the duration (e.g., 2:03 instead of 2:3) as well
Functions to write: You are to write the following seven functions for vour main program to call Function Name What does the function do No Categ 1ValidationisTimeValid * Takes one string parameter (call start time) ** Returns true if the parameter is a valid call start time Should be 6 digits long First 2 digits: Hour, between 00 and 23 Middle 2 digits: Minute, between 00 and 59 Last 2 digits: Second, between 00 and 59 * * * false otherwise Validation | 1sPhoneNumValid|※ Takes one string parameter (phone number) Returns true if the parameter is a valid phone number -Should be 12 characters long *" Starting with +1, +33, or +852 false otherwise 3 Validation isDurationValid * Takes one string parameter (duration) ** Returns true if the parameter is a valid duration string * Should be less than 10 characters long * consisting of number digits between 0 and 9 false otherwise ** * Returns a formatted (HH MM:SS) duration string Takes one string parameter (duration) 4FOormatting formatl ime Example parameter / return values . 110054""11:00:54" . "145316" 14:53:16" 5 Formatting getCountry * Takes one string parameter (phone number) Returns a 3-alpha country code string Country code +1> "NA" Country code +33 → "FR" Country code +852 → "IIK'
Formatting | get Local Phone | Takes one string parameter (phone number) * Returns a formatted local phone number string Country code +1 ""+12062812000" "(206) -281-2000" Country code +33 “OX XX XXXXXX" . "+33140205990" "01 40 20 59 90" Country code +852 . "+85223677065" "2367 7065" You don't have to check if it's valid integer format Converting | stringTo Integer | ※ Takes one string parameter which is a valid integer ** Returns an integer Can be done in a single line: use stoi() function Your main program will call the validation functions FIRST on the data it reads from the file. If a data item is not valid, then your main program will display an error indication for that item (see below) instead of trving to format the data.
Error Handling Your main program should handle incorrectly formatted data field gracefully Consider the following input file phonelog2.txt - Notepad File Edit Format View Hel,p 12 +12068372045 abc 081350 12068372045 0000000000 Here's how it should look when you run with this file File Name :phoneLog2.txt Time ERROR 08:13:50 ERROR Country Phone Number NA Duration (206)-837-2045 -1:-1 ERROR Program Stvle Your program needs to be orderly and readable. If you are working a development team and don't write clean looking code, you will be unpopular among your colleagues and may not work on that team very long Variables should be given descriptive names that start with a lowercase letter and obey the camelCase convention. Functions should be given descriptive names that start with an uppercase letter and obey the CamelCase convention. First word of a function name typically should be a verb At the start of your file you should have a header comment that gives the title of the assignment, the purpose what class this is for, and your name. Here is an example of what that could look like
// Title: Lab 1 - PhoneCalls.cpp // Purpose: read in a list of phone call records from a file, and output them /I in a more user - friendly format to the standard output (cout). // Class: CSC 2430 Spring 2019 // Author: Taiwoo Park Each subordinate function should also start with a header that describes what it does, it's parameters, what it returns, and how errors are handled. Here is an example: // Produce user friendly version of call start time // Params: string of exactly 6 characters in format hhmmss // Returns: new string formatted HHMASS // Format Error: ERROR if param is not a valid time string You should include additional comments in your code to describe what you are doing. If it is hard to understand what a variable is for, add a comment after it. It possible, though, to put in too many comments, so be judicious and make sure you have time left to do well in your other classes when it comes to commenting
You should adopt a consistent style for how you format your curly braces 3. Do it the same way throughout your file. Make sure you indent lines properly If you call open to open a file and it opens successfully, then you should call close to close it when you are done Don't use global variables Global variables sometimes are appropriate, but not in the assignments we will be giving this quarter Submitting your code Your solution should be contained with in a single C++ file, and it must be named "PhoneCalls.cpp Do not use precompiled headers (such as "stdafx.h" or "pchh"). For more information on this, ask the nstructor In three days from the announcement of this assignment, a zyLabs autograder will be available in the zyBooks Chapter 1. Go submit your file there. zyLabs autograder will run unit tests for your functions as well as input/output tests. You have unlimited opportunities of submission for autograding. You may want to submit an incomplete source code (e.g., not all functions are implemented) to check if your currently implemented functions pass the tests before your full source code submission. Take the full advantage of the autograder Grading Correctness is essential. Make sure your solution builds as described above and correctly handles both "phoneLog1.txt" and "phoneLog2.txt." We will test on other input file(s) with more number of data records, as well. Even if your code passes all zyLabs autograder tests, points may be taken off for Not following the design described above Not adhering to style guidelines described above Using techniques not presented in class Programming error not caught by other testing Not following good programming practices
0 0
Add a comment Improve this question Transcribed image text
Answer #1

// C++ program to read a list of phone calls from file and display in formatted manner on console

#include <iostream>

#include <string>

#include <iomanip>

#include <fstream>

#include <sstream>

using namespace std;

// function declaration

bool isTimeValid(string start_time);

bool isPhoneNumValid(string phone_number);

bool isDurationValid(string duration);

string formatTime(string duration);

string getCountry(string phone_number);

string getLocalPhone(string phone_number);

int stringToInteger(string str);

int main() {

               string filename;

               string start_time, phone_number, duration;

               cout<<"File Name:";

               cin>>filename;

               ifstream fin(filename.c_str());

               if(fin.is_open())

               {

                              cout<<left<<setw(10)<<"Time"<<left<<setw(9)<<"Country"<<left<<setw(16)<<"Phone Number"<<left<<"Duration"<<endl;

                              while(!fin.eof())

                              {

                                             fin>>start_time>>phone_number>>duration;

                                             if(isTimeValid(start_time)){

                                                            string modTime = start_time.substr(0,2)+":"+start_time.substr(2,2)+":"+start_time.substr(4);

                                                            cout<<left<<setw(8)<<modTime<<" ";

                                             }else

                                                            cout<<left<<setw(10)<<"ERROR";

                                             if(isPhoneNumValid(phone_number))

                                             {

                                                            cout<<left<<setw(2)<<getCountry(phone_number)<<"       "<<left<<setw(14)<<getLocalPhone(phone_number)<<" ";

                                             }else

                                                            cout<<left<<setw(9)<<"ERROR"<<left<<setw(16)<<"ERROR";

                                             if(isDurationValid(duration))

                                                            cout<<left<<formatTime(duration);

                                             else

                                                            cout<<left<<"-1:-1";

                                             cout<<endl;

                              }

               }else

                              cout<<"Failed to open file"<<endl;

               return 0;

}

// function to check if the start time is valid

bool isTimeValid(string start_time)

{

               if(start_time.length() != 6)

                              return false;

               for(size_t i=0;i<start_time.length();i++)

                              if(start_time[i] < '0' || start_time[0] >'9')

                                             return false;

               int hour = stringToInteger(start_time.substr(0,2));

               int min = stringToInteger(start_time.substr(2,2));

               int sec = stringToInteger(start_time.substr(4,2));

               if(hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 59)

                              return false;

               return true;

}

// function to check if the phone number is valid

bool isPhoneNumValid(string phone_number)

{

               if(phone_number.length() != 12)

                              return false;

               if((phone_number.substr(0,2).compare("+1") != 0) && (phone_number.substr(0,3).compare("+33") != 0) && (phone_number.substr(0,4).compare("+852") != 0))

                              return false;

               return true;

}

// function to check if the duration is valid

bool isDurationValid(string duration)

{

               if(duration.length() > 9)

                              return false;

               for(size_t i=0;i<duration.length();i++)

                              if(duration[i] < '0' || duration[0] >'9')

                                             return false;

               return true;

}

// function format and return the duration

string formatTime(string duration)

{

               int dur = stringToInteger(duration);

               int mins = dur/60;

               int secs = dur - (mins*60);

               stringstream minss, secss;

               minss<<mins;

               secss<<setw(2)<<setfill('0')<<secs;

               string retStr = minss.str()+":"+secss.str();

               return retStr;

}

// function to format and return the country of the associated phone number

string getCountry(string phone_number)

{

               if(phone_number.substr(0,2).compare("+1") == 0)

                              return "NA";

               else if(phone_number.substr(0,3).compare("+33") == 0)

                              return "FR";

               else

                              return "HK";

}

// function to format and return the local phone number

string getLocalPhone(string phone_number)

{

               if(phone_number.substr(0,2).compare("+1") == 0)

                              return("("+phone_number.substr(2,3)+")-"+phone_number.substr(5,3)+"-"+phone_number.substr(8));

               else if(phone_number.substr(0,3).compare("+33") == 0)

               {

                              string mod_phone = "0"+phone_number.substr(3,1);

                              size_t index = 4;

                              while(index < phone_number.length())

                              {

                                             mod_phone = mod_phone +" "+ phone_number.substr(index,2);

                                             index = index + 2;

                              }

                              return mod_phone;

               }else

               {

                              return(phone_number.substr(4,4)+" "+phone_number.substr(8));

               }

}

// function to convert string to integer

int stringToInteger(string str)

{

               return stoi(str);

}

//end of program

Output:

Input file:

110054 +12062812000 5912 091233 +33140205990 364 145316 +85223677065 180 12 +12068372045 аЬс 081350 12068372045 0000000000

Output:

File Name: phoneLog1.txt Time 11:00:54 NA 09:12:33 FR 14:53:16 HK ERROR 08:13:50 ERROR ERROR Country Phone Number Duration (2

Add a comment
Know the answer?
Add Answer to:
I need help with this assignment in C++, please! *** The instructions and programming style detai...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with the following code... Instructions: This lab builds on the skills from Lab...

    I need help with the following code... Instructions: This lab builds on the skills from Lab 2c, in which you read data values from a file and kept a count of the number of invalid values. In this lab, your program will be using the same code to read each data entry from the file, but you will also save each value in an array named allMags after each is read in. When all values in the file have been...

  • can you please follow all the instructions ? The answers that I got has either missing...

    can you please follow all the instructions ? The answers that I got has either missing range for loop or one funtion . Read the instructions carefully. At least 10% will be deducted if the instructions are not followed. For general lab requirements, see General Lab Requirements. Do not prompt the user for input during the execution of your program. Do not pause at the end of the execution waiting for the user's input. Notes 1. Your program should use...

  • Write a program **(IN C)** that displays all the phone numbers in a file that match the area code...

    Write a program **(IN C)** that displays all the phone numbers in a file that match the area code that the user is searching for. The program prompts the user to enter the phone number and the name of a file. The program writes the matching phone numbers to the output file. For example, Enter the file name: phone_numbers.txt Enter the area code: 813 Output: encoded words are written to file: 813_phone_numbers.txt The program reads the content of the file...

  • C++ assignment help! The instructions are below, i included the main driver, i just need help...

    C++ assignment help! The instructions are below, i included the main driver, i just need help with calling the functions in the main function This assignment will access your skills using C++ strings and dynamic arrays. After completing this assignment you will be able to do the following: (1) allocate memory dynamically, (2) implement a default constructor, (3) insert and remove an item from an unsorted dynamic array of strings, (4) use the string class member functions, (5) implement a...

  • Help with programming in C++ Phase 1 is complete, please help with phase 2. Thank you....

    Help with programming in C++ Phase 1 is complete, please help with phase 2. Thank you. Phase 1 You must design 3 algorithms, and provide both a flow chart and pseudo code for the algorithms.    Algorithm descriptions: Given an integer parameter named current_number and two constant global variables: const int MIN_NUMBER = 1; const int MAX_NUMBER = 8; Create an algorithm named forward, that will advance ONE value through a sequence of numbers 1, 2, 3 ... MAX_NUMBER. In...

  • C++ programming help. The only change you have to make is in current program, where it...

    C++ programming help. The only change you have to make is in current program, where it says "your code goes here", do not make any changes to any other files, they are just there to show you. This code should be written for arbitrary data, not specifically for this sequence of data. The only place you need to write a code is marked YOUR CODE GOES HERE. You have been supplied a file with data in it (data2.txt). The line...

  • C++ programming For this assignment, write a program that will act as a geometry calculator. The...

    C++ programming For this assignment, write a program that will act as a geometry calculator. The program will be menu-driven and should continue to execute as long as the user wants to continue. Basic Program Logic The program should start by displaying a menu similar to the following: Geometry Calculator 1. Calculate the area of a circle 2. Calculate the area of a triangle 3. Quit Enter your choice(1-3): and get the user's choice as an integer. After the choice...

  • /************************************************************************************ * Program: PRG/420 Week 5 * Purpose: Week 5 Coding Assignment * Programmer: TYPE YOUR...

    /************************************************************************************ * Program: PRG/420 Week 5 * Purpose: Week 5 Coding Assignment * Programmer: TYPE YOUR NAME HERE * Class: PRG/420 * Creation Date: TYPE TODAY'S DATE HERE ************************************************************************************* * Program Summary: * This program converts a given date to a string. * The code includes exception handling for a ParseException. ************************************************************************************/ package prg420week5_codingassignment; import java.util.*; // wildcard to import all the util. classes import java.text.*; // wildcard to import all the text classes public class PRG420Week5_CodingAssignment { public static...

  • I need the following written in Java please, thank you ' We want you to implement...

    I need the following written in Java please, thank you ' We want you to implement a java class that will show details on users and throw exceptions where needed. The following requirements specify what fields you are expected to implement in your User class: - A private String firstName that specifies the first name of the user - A private String lastName that specifies the last name of the user - A private int age that specifies user's age...

  • help please Program Requirements You are given 1 file: Lab1Tests.java. You need to complete 1 file:...

    help please Program Requirements You are given 1 file: Lab1Tests.java. You need to complete 1 file: UWECPerson.java uWECPerson.java UWECPerson uwecld: int firstName: String lastName : String +UWECPerson(uwecld: int, firstName : String, lastName: String) +getUwecid): int setUwecld(uwecld: int): void +getFirstName): String +setFirstName(firstName: String): void getLastName): String setLastName(lastName: String): void +toString): String +equals(other: Object): boolean The constructor, accessors, and mutators behave as expected. The equals method returns true only if the parameter is a UWECPerson and all instance variables are equal. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT