Unable to Count Number of Digits as the Input - c++

My Program: To get input from the user about personal details and then output the information.
My Problem: The program is unable to count the number of digits as the input for Phone Number field. It accepts more than 10-digits as an input for the phone number.
My Goal: To check the input for 'Phone Number' and make sure that the number is 10-digits.
My Code:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Personal_Details
{
public:
void setFirstName (string newFirstName);
void setLastName (string newLastName);
void setBirthdate (int newBirthday);
void setEMail (string newEMail);
void setPhoneNumber (int newPhoneNumber);
void QUESTIONS();
string getFirstName();
string getLastName();
string getEMail();
int getPhoneNumber();
int getBirthdate();
private:
string FirstName;
string LastName;
string EMail;
int PhoneNumber;
int Birthdate;
};
void Personal_Details :: setFirstName (string newFirstName)
{
FirstName = newFirstName;
}
void Personal_Details :: setLastName (string newLastName)
{
LastName = newLastName;
}
void Personal_Details :: setBirthdate (int newBirthdate)
{
Birthdate = newBirthdate;
}
void Personal_Details :: setEMail (string newEMail)
{
EMail = newEMail;
}
void Personal_Details :: setPhoneNumber (int newPhoneNumber)
{
PhoneNumber = newPhoneNumber;
}
string Personal_Details :: getFirstName()
{
return FirstName;
}
string Personal_Details :: getLastName()
{
return LastName;
}
int Personal_Details :: getBirthdate()
{
return Birthdate;
}
string Personal_Details :: getEMail()
{
return EMail;
}
int Personal_Details :: getPhoneNumber()
{
if (PhoneNumber>12)
{
cout <<"INVALID. Program will now close.";
}
system ("PAUSE");
return PhoneNumber;
}
void Personal_Details :: QUESTIONS()
{
cout << "A.) Enter the following details:-" << endl <<endl;
cout << "First Name: ";
getline (cin, FirstName);
cout << endl;
cout << "Last (Family) Name: ";
getline (cin, LastName);
cout << endl;
cout << "Birthdate: ";
cin >> Birthdate;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "Email Address: ";
getline (cin, EMail);
cout << endl;
cout << "Phone Number: ";
cin >> PhoneNumber;
cout << endl;
cout<< FirstName <<" "<< LastName << endl
<<"Birthdate: "<< Birthdate << endl
<<"Email ID: "<< EMail << endl
<<"Phone Number: "<< PhoneNumber << endl;
}
int main()
{
Personal_Details NewContact;
cout << "- Add New Contact Information -" << endl << endl;
cout << "Note: Please type in only intergers (numbers) for 'Birthdate' and 'Phone Number' field. Also, phone number should be less than/or equal to 10 digits." << endl;
cout << "Else, this program will terminate abruptly." << endl << endl;
NewContact.QUESTIONS();
cout << endl << endl;
cout << "Press Any Key to Exit.";
cin.ignore();
cin.get();
return 0;
}
Please can you review and check why I am not able to input a real 10-digit phone number? I am new to C++, so I am unable to figure out a solution. Thanks for your help!

You are storing the phone number as an int, but the range of integers is –2,147,483,648 to 2,147,483,647; entering a 10 digit number outside of that range results in overflow and may be what is crashing your program.
You may want to read in the phone number as a string, check each character for validity, and process it however you need to (e.g.: a variable for area code, a variable of 7 digit number, reject out of range input and re-prompt).

Related

How to edit and delete csv records

I am working on a program through Xcode, it is supposed to read a file and perform various functions:
displayMenu,
doDisplay,
doView,
doAdd,
doEdit,
doDelete.
I have gotten it all to work except the do edit and do delete functions, and I can't find anything online that helps with my particular situation.
The user is supposed to pick the course they want to edit, and be able to edit the term, year, start date, end date, etc.
Thank you in advance.
Here is my code attached.
Here are instructions if you are curious:
Course Menu
=====================
d - Display list of courses
v - View course details
a - Add a course
e - Edit a course
d - Delete a course
x - Exit program
Requirements
Given a comma-delimited text file named courses.csv Download
courses.csv(click to download) that stores the starting data for the
program.
A course is an organized presentation about a particular subject that includes Term, Year, Start Date, End Date, Course Name, Class ID, Section, Meeting Days, Location (online, hybrid, or on-campus), Meeting Information, Instructor, Units.
For the view, edit, and delete commands, display an error message if
the user selects an invalid course.
Define a data structure to store the data for each course.
When you start the program, it should read the contacts from the
comma-delimited text file and store them in a vector of courses.
When reading data from the text file, you can read the line and
separate the field by an all text up to the next comma (ex. getline()
function).
When you add, edit or delete a contact, the change should be saved to
the text file immediately. That way, no changes are lost, even if the
program crashes later.
For demonstration, you need to be able to view/add/edit/delete at
least 3 courses listed
Here is my code: https://pastebin.com/HkEE9HBD
////myApp.cpp
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include "course.h"
#include "utils.h"
using namespace std;
char menu();
int main() {
vector<courseType> list;
readData(list);
char ch = 'x';
do {
cout << endl;
ch = menu();
switch (ch) {
case 'l':
// function handler
doDisplay(list);
break;
case 'v':
doView(list);
break;
case 'a':
doAdd(list);
break;
case 'e':
doEdit(list);
break;
case 'd':
doDelete(list);
break;
default:
cout << "Please enter valid choice" << endl;
}
} while (ch != 'x');
cout << "Exit the program" << endl;
return 0; // exit the program successfully
}
/**
* Display application menu
*/
char menu() {
cout << "Course Menu" << endl;
cout << "=====================" << endl;
cout << "l - Display list of courses" << endl;
cout << "v - View course details" << endl;
cout << "a - Add a course" << endl;
cout << "e - Edit a course" << endl;
cout << "d - Delete a course" << endl;
cout << "x - Exit program" << endl << endl;
cout << "Enter choice: ";
char ch;
cin >> ch;
cout << endl;
return ch;
}
//courseImp.cpp
#include <string>
#include "course.h"
#include <iostream>
using namespace std;
courseType::courseType() {
term = "";
year = 0.0;
startDate = "";
endDate = "";
courseName = "";
section = "";
classID = 0.0;
meetingDays = "";
location = "";
meetingInfo = "";
instructor = "";
units = 0.0;
}
courseType::~courseType() {
}
//List of Acessor and Getter Methods For Each Variable
void courseType::setTerm(string term) {
this ->term = term;;
}
string courseType::getTerm() {
return term;
}
void courseType::setYear(string temp) {
this ->temp = temp;
}
string courseType::getYear() {
return temp;
}
void courseType::setStart(string startDate) {
this ->startDate = startDate;
}
string courseType::getStart() {
return startDate;
}
void courseType::setEnd(string endDate) {
this ->endDate = endDate;
}
string courseType::getEnd() {
return endDate;
}
void courseType::setName(string courseName) {
this ->courseName = courseName;
}
string courseType::getName() {
return courseName;
}
void courseType::setSection(string section) {
this ->section = section;
}
string courseType::getSection() {
return section;
}
void courseType::setID(string tempC) {
this->tempC = tempC;
}
string courseType::getID() {
return tempC;
}
void courseType::setDays(string meetingDays) {
this ->meetingDays = meetingDays;;
}
string courseType::getDays() {
return meetingDays;
}
void courseType::setLocation(string location) {
this ->location = location;
}
string courseType::getLocation() {
return location;
}
void courseType::setInfo(string meetingInfo) {
this ->meetingInfo = meetingInfo;
}
string courseType::getInfo() {
return meetingInfo;
}
void courseType::setInstructor(string instructor) {
this ->instructor = instructor;
}
string courseType::getInstructor() {
return instructor;
}
void courseType::setUnits(string tempU) {
this ->tempU = tempU;
}
string courseType::getUnits() {
return tempU;
}
//utils.cpp
#include <iostream>
#include <iomanip>
#include "utils.h"
#include "course.h"
#include <cstdlib>
#include <iostream>
#include <utility>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
//Function Dislays list of Courses
void doDisplay(vector<courseType>& list) {
cout << left << setw(10) << "Course List" << endl;
cout << "==============================" << endl;
for(int i = 0; i < list.size(); i++){
cout << left << setw(10) << list[i].getName() << "" << endl << endl;
}
}
//Function views individual course
void doView(vector<courseType>& list) {
int chv = 0;
for(int i = 0; i < list.size(); i++){
cout << i+1 << ". " << list[i].getName() << "" << endl << endl;
}
cout << "Please choose a course you want to view: ";
cin >> chv;
cout << endl;
if(chv<list.size()+1)
{
cout << left << setw(10) << "Term" << setw(10) << "Year"
<< setw(15) << "Start Date" << setw(15) << "End Date"
<< setw(35) <<"Course Name" << setw(15) << "Section"
<< setw(12) << "Class ID" << setw(17) << "Meeting Days"
<< setw(15) << "Location" << setw(20) << "Meeting Info"
<< setw(15) << "Instructor" << "Units" << endl;
cout << "=============================================================================================";
cout << "=============================================================================================" << endl;
chv=chv-1;
cout << left << setw(10) << list[chv].getTerm() << "" << setw(10) << list[chv].getYear() <<
"" << setw(15) << list[chv].getStart() << "" << setw(15) << list[chv].getEnd() << "" <<
setw(35) << list[chv].getName() << "" << setw(15) << list[chv].getSection() << "" <<
setw(15) << list[chv].getID() << "" << setw(15) << list[chv].getDays() << "" <<
setw(17) << list[chv].getLocation() << "" << setw(20) << list[chv].getInfo() << "" <<
setw(15) << list[chv].getInstructor() << "" << setw(10) << list[chv].getUnits() << "" << endl;
}
}
//Function Adds Courses
void doAdd(vector<courseType>& list) {
char choice;
char delim = ',';
string term = "";
float year = 0.0;
string start = "";
string end = "";
string name = " ";
string section = "";
float id = 0.0;
string days = "";
string location = "";
string info = "";
string instructor = "";
float units = 0.0;
ofstream outMyStream (FILE_NAME, ios::app);
do {
cout << "Enter term: " ;
cin.ignore();
getline(cin, term);
cout << "Enter year: ";
cin >> year;
cin.ignore();
cout << "Enter start date: ";
getline(cin, start);
cout << "Enter end date: ";
getline(cin, end);
cout << "Enter course name: ";
getline(cin, name);
cout << "Enter course section: ";
getline(cin, section);
cout << "Enter course ID: ";
cin >> id;
cin.ignore();
cout << "Enter meeting Days : ";
getline(cin, days);
cout << "Enter meeting location: ";
getline(cin, location);
cout << "Enter meeting information: ";
getline(cin, info);
cout << "Enter instructor name: ";
getline(cin, instructor);
cout << "Enter units: ";
cin >> units;
cin.ignore();
outMyStream << term << delim << year << delim << start << delim << end << delim << name << delim << section << delim
<< id << delim << days << delim << location << delim << info << delim << instructor << delim << units << endl;
cout << "\nEnter another Record? (Y/N) ";
cin >> choice;
if (choice != 'Y' and choice != 'y' and choice != 'N' and choice != 'n') // if needed add input
cout << choice << " is not a valid option. Try agian" << endl;
}while (choice != 'N' && choice != 'n');
{
outMyStream.close();
}
}
//Function Edits Courses
void doEdit(vector<courseType>& list) {
}
//Function Deletes Courses
void doDelete(vector<courseType>& list) {
}
//Function Reads Data from "courses.csv"
void readData(vector<courseType>& list) {
ifstream inFile;
fstream fin;
inFile.open(FILE_NAME);
string line;
while (getline(inFile, line)) {
string term;
float year;
string startDate;
string endDate;
string courseName;
string section;
float classID;
string meetingDays;
string location;
string meetingInfo;
string instructor;
float units;
string temp;
string tempU;
string tempC;
stringstream ss(line);
getline(ss, term, ',');
getline(ss, temp, ',');
year = atoi(temp.c_str());
getline(ss, startDate, ',');
getline(ss, endDate, ',');
getline(ss, courseName, ',');
getline(ss, section, ',');
getline(ss,tempC,',');
classID = atoi(tempC.c_str());
getline(ss, meetingDays, ',');
getline(ss, location, ',');
getline(ss, meetingInfo, ',');
getline(ss, instructor, ',');
getline(ss,tempU,',');
units = atoi(tempU.c_str());
courseType c;
c.setTerm(term);
c.setYear(temp);
c.setStart(startDate);
c.setEnd(endDate);
c.setName(courseName);
c.setSection(section);
c.setID(tempC);
c.setDays(meetingDays);
c.setLocation(location);
c.setInfo(meetingInfo);
c.setInstructor(instructor);
c.setUnits(tempU);
list.push_back(c);
}
inFile.close();
}
//course.h
#pragma once
#include <string>
#include <sstream>
using namespace std;
class courseType {
public:
// mutator methods - set
void setTerm(string term);
void setYear(string temp);
void setStart(string startDate);
void setEnd(string endDate);
void setName(string courseName);
void setSection(string section);
void setID(string tempC);
void setDays(string meetingDays);
void setLocation(string location);
void setInstructor(string instructor);
void setInfo(string meetingInfo);
void setUnits(string tempU);
// ...
// accessor methods - get
string getTerm();
string getYear();
string getStart();
string getEnd();
string getName();
string getSection();
string getID();
string getDays();
string getLocation();
string getInstructor();
string getInfo();
string getUnits();
// ...
// Other member methods
// ...
courseType();
~courseType();
protected:
// tbd
private:
// data structures
string term;
float year;
string startDate;
string endDate;
string courseName;
string section;
float classID;
string meetingDays;
string location;
string meetingInfo;
string instructor;
float units;
string temp;
string tempU;
string tempC;
};
//utils.h
#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include "course.h"
using namespace std;
const string FILE_NAME = "courses.csv";
// Prototype functions...
void doDisplay(vector<courseType>& list);
void doView(vector<courseType>& list);
void doAdd(vector<courseType>& list);
void doEdit(vector<courseType>& list);
void doDelete(vector<courseType>& list);
void readData(vector<courseType>& list);
//courses.csv
Spring,2022,1/24/2022,5/20/2022,Discrete Structures,CS-113-02,085689,T TH,On-Campus,Newark,Pham,3
Spring,2022,1/24/2022,5/20/2022,Programming W/ Data Structures,CS-124-02,084371,M W,On-Campus,Zoom,Pham,3
Spring,2022,1/24/2022,5/20/2022,Programming W/ Data Structures,CS-124-03,085698,T TH,Online,Newark,Pham,3
Spring,2022,1/24/2022,5/20/2022,JavaScript for Web Development,CS-175-01,084377,M,Online,Zoom,J. Pham,4
Spring,2022,1/24/2022,5/20/2022,Beginner Java,CS-125-05,089434,TH,Online,Zoom,Gao,3
Ah, college professors... Store things in csv files but act like it's a database.
What I would do is design a set of classes that mirror your data. So you'd have a class called Course (for instance). And you'd have another called Curriculum, perhaps, and it would store a std::vector of Courses.
You would then need a readFromCSV and writeToCSV pair of methods. You would want more methods for the various actions you have to perform, and any methods that modify data should then call writeToCSV automatically.
Does that make sense?
You can build it by first just writing the read and write methods and just make sure your output file looks identical to your input file.
Then start implementing the data update methods, one at a time.
Not too bad.

Can Someone Explain Why My Getter Function Doesn't Call?

I'm writing some code to create a student class and a menu that allows the user to input and display information. Im running into some issues getting my GetName function to call. Here is my code:
#include <iostream>
using namespace std;
class Student {
string FirstName, LastName, Birthday;
int MNumber, Age;
float GPA;
public:
void GetName(){
cout << "Please enter your First Name." << endl;
cin >> FirstName;
cout << "Please enter your Last Name." << endl;
cin >> LastName;
cout << FirstName << ", " << LastName << endl;
}
};
int main () {
Student GetName;
return 0;
}
}
You're not calling the "Getname" method inside main program.
#include <iostream>
using namespace std;
class Student {
string FirstName, LastName, Birthday;
int MNumber, Age;
float GPA;
public:
void GetName(){
cout << "Please enter your First Name." << endl;
cin >> FirstName;
cout << "Please enter your Last Name." << endl;
cin >> LastName;
cout << FirstName << ", " << LastName << endl;
}
};
int main () {
Student getName;
getName.GetName();
return 0;
}

How can I access elements of a vecotor in C++

Actually, I am rookie, and I started to learning this language a few months age. Now, I confronted with an insoluble issue. I devised a program to get information of numerous employee's specification and store it in a vector. In order to acquire better performance, I designed a class named "Employee", and defined a function to give some options to user, like adding new employee, promotion a specific employee's salary and so on.
I defined my matching criterion through operators, but there is an error in program, and that is when I want to display, the output is completely weird. it looks like a some kind of Chinese letter :-)
here is my code:
Thanks
My major problem is when it comes displaying employee's specification
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <sstream>
using namespace std;
class Employee
{
public:
Employee(string FirstName, string LastName, int age , double Salary, bool Status ) ://constructor
fName(FirstName), lName(LastName), EmpAge(age), EmpSalary(Salary), RecruitmentStatus(Status) {};
void setSalary(const double&);
void SetRecruitmentStatus(const bool&);
void Promote(const double&);
//====================================//
operator const char* ()
{
ostringstream formattedOutput;
formattedOutput << this->fName.c_str() << " " << (this->lName.c_str()) << " | " << this->EmpAge << " | " << this->EmpSalary << ((RecruitmentStatus) ? "Working" : "Fired");
string output = formattedOutput.str();
return output.c_str();
}
bool operator == (const Employee& anotherEmployee)const
{
return (this->lName == anotherEmployee.lName);
}
bool operator < (const Employee& anotherEmployee)const
{
return (this->EmpSalary < anotherEmployee.EmpSalary);
}
private:
string fName, lName;
int EmpAge;
double EmpSalary;
bool RecruitmentStatus;
};
void Employee::setSalary(const double& income)
{
this->EmpSalary += income;
}
void Employee::SetRecruitmentStatus(const bool& Status)
{
this->RecruitmentStatus = Status;
}
void Employee::Promote(const double& Promotion)
{
this->EmpSalary += Promotion;
}
template <typename T>
void displayElements(T& input)
{
for (auto iterator = input.begin();
iterator != input.end(); iterator++)
{
cout << *iterator << endl;
}
}
void selection(int&);
Employee getNewEmp(void);
int main()
{
vector<Employee> Records;
int ID;
do
{
selection(ID);
switch (ID)
{
case 1:
{
Records.push_back(getNewEmp());
break;
}
case 2:
{
cout << "please enter last name of the employee you want to change his/her recruitment'status: ";
string lastName; cin >> lastName; cout << endl;
auto memberLocation = find(Records.begin(), Records.end(), lastName.c_str());
break;
}
case 3:
{
cout << "please enter last name of the employee you want to promote his/her recruitment'salary: ";
string lastName; cin >> lastName; cout << endl;
auto memberLocation = find(Records.begin(), Records.end(), lastName.c_str());
break;
}
default:
{
if (ID !=4)
{
cout << "Wrong selection!\nThe program will be closed after a few seconds\n";
exit(1);
}
}
}
} while (ID != 4);
displayElements(Records);
cout << "Thanks for using this program\n";
return 0;
}
void selection(int& input)
{
system("cls");
cout << "please Choose one of these option:\n"
"1. add a new employee\n"
"2. changing an employee status\n"
"3. Promote an employee's salary\n"
"4. exit : ";
cin >> input;
}
Employee getNewEmp(void)
{
system("cls");
string firstName, lastName;
cout << "first name:"; cin >> firstName; cout << endl;
cout << "last name:"; cin >> lastName; cout << endl;
int age;
cout << "Age: "; cin >> age; cout << endl;
double salary;
cout << "Offered Salary: "; cin >> salary; cout << endl;
bool Status;
cout << "Is he/she working(1) or got fired(0) : "; cin >> Status; cout << endl;
return Employee(firstName, lastName, age, salary, Status);
}

How to modify values inside a data file in C++

I'm trying to allow the user to modify values from a data file. I'm using class members to hold the value as well as an array
#include <iostream>
#include <fstream>
using namespace std;
class student
{
private:
string stuID;
string lastN;
string firstN;
float GPA;
int numb_of_enrolled;
public:
void displayAll();
void setAll(string StuID, string LastN, string FirstN, float gpa, int nof);
};
const int SIZE = 30;
int main()
{
ifstream inFile;
int option, count, scount = 0, cIndex;
student stuFile[SIZE];
string sID, sLN, sFN;
float sgpa;
int snof;
char repeat = 'y';
inFile.open("Students.dat", ios::in);
cout << "MENU\n";
cout << "3. Change an Existing Record's Fields\n";
cout << "What would you like to do?: ";
cin >> option;
cin.ignore();
switch(option) {
case 3:
inFile >> sID >> sLN >> sFN >> sgpa >> snof;
cout << "There are 19 Students in this data file\n";
cout << "Enter an Index from 0 - 19: ";
cin >> cIndex;
cin.ignore();
stuFile[cIndex].setAll(sID, sLN, sFN, sgpa, snof);
stuFile[cIndex].displayAll();
}
}
void student::displayAll()
{
cout << "Student ID: " << stuID << endl;
cout << lastN << ", " << firstN << endl;
cout << numb_of_enrolled << " Classes taken this Semester\n";
cout << "Current GPA is: " << GPA << "\n\n";
}
void student::setAll(string StuID, string LastN, string FirstN, float gpa, int nof)
{
stuID = StuID;
lastN = LastN;
firstN = FirstN;
GPA = gpa;
numb_of_enrolled = nof;
}
So the data file has 19 records inside of it. Case 3 works but not how it should. If I enter 3, it doesn't go to the third record inside of it but it stays at 0. Even if I use .eof(), it would still be stuck at element 0. How can I make it so that I'm able to get to the record I want?
You need to loop for N lines for the cIndex, declare int i and do this code
case 3:
cout << "There are 19 Students in this data file\n";
cout << "Enter an Index from 0 - 19: ";
cin >> cIndex;
cin.ignore();
for(i=0;i<cIndex;i++) {
inFile >> sID >> sLN >> sFN >> sgpa >> snof;
}
stuFile[cIndex].setAll(sID, sLN, sFN, sgpa, snof);
stuFile[cIndex].displayAll();
inFile.clear();
inFile.seekg(0);

How to read first and last name with void function

I can easily create a void function to output something like a header, but I cannot get a program to read a user's input and then output it to them.
ie. Have a program say "Please enter your first name" and then output "You entered: (what they put)"
An example of what I have:
#include<iostream>
#include<conio.h>
#include<iomanip>
#include<fstream>
using namespace std;
void namefn()//namefn prototype
int main(){
string firstName,lastName;
return 0;
}
void namefn(string firstName, string lastName){
cout<<"please enter your first and last name "<<endl;
}
Use cin to read, is in iostream.
i.e.
cin >> firstName;
cout << "enter your first and last name:";
cin >> firstName >> lastName;
cout << firstName << " " << lastName;
if you want the program to display the first name and last name separately then this:
cout << "enter you first name:";
cin >> firstName;
cout << firstName << endl;
cout << "Enter your last name:";
cin >> lastName;
cout << lastName << endl;
Try this:
#include <iostream>
#include <string>
void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
std::cout << "You are " << firstName << " " << lastName << std::endl;
}
int main(){
std::string firstName;
std::string lastName;
std::cout << "Please enter your first and last name " << std::endl;
std::cin >> firstName >> lastName;
displayFirstAndLast(firstName, lastName);
return 0;
}
I think, that you want something like this.
Or with something like "header"
#include <iostream>
#include <string>
void displayFirstAndLast(const std::string& firstName, const std::string& lastName);
int main(){
std::string firstName;
std::string lastName;
std::cout << "Please enter your first and last name " << std::endl;
std::cin >> firstName >> lastName;
displayFirstAndLast(firstName, lastName);
return 0;
}
void displayFirstAndLast(const std::string& firstName, const std::string& lastName)
{
std::cout << "You are " << firstName << " " << lastName << std::endl;
}