How to store user input in an int array - c++

I need to ask the user to input 8 zip codes and then store them in an array of integers and then to output them one by one , each being in a new line.These two things should be done in separate functions. But when it runs the code first time it shows only menu, then second time in loop when i enter L and input 8 zipcodes it shows this error
Enter your choice: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string(in here optionInChar=optionInString.at(0);)
using namespace std;
void DisplayCityZipCodes();
int LoadCityZipCodes(int ZipCodes[],int SIZE);
void DisplayCityZipCodes(int ZipCodes[],int SIZE);
void DisplayMenu();
char GetOption();
int main(){
int const SIZE=8;
int ZipCodes[SIZE]={0};
bool moreWork=true;
option=GetOption();
while(moreWork) {
DisplayMenu();
option=GetOption();
switch(option){
case 'L':
ZipCodes[SIZE]= LoadCityZipCodes(ZipCodes, SIZE);
break;
cout<<"D";
case 'D': DisplayCityZipCodes(ZipCodes, SIZE);
break;
}
}
}
void DisplayMenu(){
cout<<" **********************\n\n";
cout<<" San Jose City Zip codes\n\n";
cout<<" **********************\n\n";
cout<<"1. Load City zip codes\n";
cout<<"2. Display all City zip codes\n";
cout<<"3. Search a City zip code\n";
cout<<"4. Reverse the City zip code List\n";
cout<<"5. Quit\n";
}
char GetOption(){
string optionInString="";
char optionInChar='a';
cout<<"\n\nEnter your choice: ";
getline(cin,optionInString);
optionInChar=optionInString.at(0);
cout<<"\n";
return optionInChar;
}
int LoadCityZipCodes(int ZipCodes[],int SIZE){
cout<<"PLease enter 8 city Zip Codes ";
int i=0;
for(;i<8;i=i+1){
cin >>ZipCodes[i];
}
return ZipCodes[i];
}
void DisplayCityZipCodes(int ZipCodes[],int SIZE){
int i=0;
for(;i<8;i=i+1){
cout<<ZipCodes[i]<<endl;
}
}

Now I have not had a hand on C++ for a long time, but this will work.
You should look on the variable declarations and some other things though.
#include<iostream>
#include<conio.h>
using namespace std;
void DisplayCityZipCodes();
void LoadCityZipCodes();
void DisplayMenu();
int const SIZE = 8;
int ZipCodes[SIZE];
int main()
{
DisplayMenu();
return 0;
}
void DisplayMenu()
{
int ch;
cout << " **********************\n\n";
cout << " San Jose City Zip codes\n\n";
cout << " **********************\n\n";
do
{
cout << "1. Load City zip codes\n";
cout << "2. Display all City zip codes\n";
cout << "3. Search a City zip code\n";
cout << "4. Reverse the City zip code List\n";
cout << "5. Quit\n";
cout << "\nPlease enter your choice:";
cin >> ch;
switch (ch)
{
case 1:
LoadCityZipCodes();
break;
case 2:
DisplayCityZipCodes();
break;
case 5:
exit(0); //You will need to include math.h for this.
default:
cout << "please enter a proper choice!";
break;
}
} while (1);
}
void LoadCityZipCodes()
{
cout << "PLease enter 8 city Zip Codes ";
for (int i=0; i<8; i++)
{
cin >> ZipCodes[i];
}
}
void DisplayCityZipCodes()
{
for (int i=0; i<8; i++)
{
cout << ZipCodes[i] << endl;
}
}
You can add remaining of your functions with case 3 and 4.
Try to debug the code and see how it work before you post :)

You need to look closer at the statements
return ZipCodes[i];
and
ZipCodes[SIZE]= LoadCityZipCodes(ZipCodes, SIZE);
In both cases you use ZipCodes[8] which is definitely out of range.
To solve both problems, don't return anything from LoadCityZipCodes (i.e. make it return void), because it already sets the values in the array.

You need to remeber that when programming we start counting at 0. That means for an array that has the size 8 all the valid indexes are: 0, 1, 2, 3, 4, 5, 6, 7. When you try to access your array with ZipCodes[8] you are asking for the 9th element which is out of range.

Related

Delete data from a dynamically allocated array in c++

I am trying to delete a record from an entered position, from a dynamically allocated array in c++, and when i try to run the program it throws an error stating
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
The insertion and displaying of the records are running perfectly fine, the only thing that throws an error is delete operation.
The Code
#include <iostream>
using namespace std;
struct employee{
string name;
int empId;
string dept;
int age;
};
employee *emp = new employee[5];
void insertData(){
for (int i = 0; i<5; i++){
cout<<"Enter the Employee name"<<endl;
cin>>emp -> name;
cout<<"Enter the Employee Id"<<endl;
cin>>emp -> empId;
cout<<"Enter the Employee Department"<<endl;
cin>>emp -> dept;
cout<<"Enter the Employee age"<<endl;
cin>>emp -> age;
}
}
void displayData(){
for (int i = 0; i < 5; ++i) {
cout<<"Employee"<<i+1<<" Data"<<endl;
cout<<"Name : "<<emp -> name<<endl;
cout<<" Employe ID : "<<emp -> empId<<endl;
cout<<"Department : "<<emp -> dept<<endl;
cout<<"Age : "<<emp -> age<<endl<<endl;
}
}
void deleteData(){
int pos;
cout<<"Enter the position you want to delete Data";
cin>>pos;
if (pos>5){
cout<<"Invalid Size please enter a size smaller than 5";
}
for (int i = pos; i < 5; ++i) {
emp[i] = emp[i+1];
}
}
int menu(){
int x;
do {
int n;
cout << "Please enter the number corresponding to an operation you want to perform\n";
cout << "1. Insert Data" << endl;
cout << "2. Display Data" << endl;
cout << "3. Delete Data" << endl;
cout << "4. Exit" << endl;
cin >> n;
switch (n) {
case 1: {
insertData();
break;
}
case 2: {
displayData();
break;
}
case 3: {
deleteData();
break;
}
case 4: {
exit(0);
}
default:
cout << "Invalid Choice, Enter a valid choice";
return 1;
}
cout<<"Press 1 to continue or 0 to exit";
cin>>x;
} while (x == 1);
}
int main() {
menu();
return 0;
}
Your code has several logic issues.
Inserting and displaying data
When you insert and display data with insertData and displayData you loop over five indices (i) but you never used that variable in your loop. You simply operate all five times on the pointer to the first element in the array.
Deleting data
You print an error message if pos is greater than 5, but then you go ahead and run the rest of the function anyway. A return would break out of the function at this point. Also, I suggest writing to std::cerr for error messages.
You iterate from pos to 4, but copy from index 5, which is out of bounds. This yields undefined behavior. You should change your bounds to i < 4. Because arrays are indexed starting at 0 you also need to start at pos - 1.
You never clear out the data in the last element. As you're only deleting one record at a time, you now it'll always be the last one that needs to be cleared.
void deleteData(){
int pos;
cout<<"Enter the position you want to delete Data";
cin>>pos;
if (pos>5){
cout<<"Invalid Size please enter a size smaller than 5";
}
for (int i = pos; i < 5; ++i) {
emp[i] = emp[i+1];
}
}
Suggested:
void deleteData() {
int pos;
cout << "Enter the position you want to delete Data ";
cin >> pos;
if (pos > 5){
cout << "Invalid Size please enter a size smaller than 5\n";
return;
}
for (int i = pos - 1; i < 4; ++i) {
emp[i] = emp[i+1];
}
emp[4].name = "";
emp[4].empId = 0;
emp[4].dept = "";
emp[4].age = 0;
}
Menu
In your menu function you should initialize x to 1, as you don't error check user input at the end.
You return in the default case, which will prevent the loop from repeating to get a valid input.
You never use the return value of menu and it may not ever return, which your compiler should warn you about. The return type should be void.
void menu() {
int x = 1;
do {
int n;
cout << "Please enter the number corresponding to an operation you want to perform\n";
cout << "1. Insert Data" << endl;
cout << "2. Display Data" << endl;
cout << "3. Delete Data" << endl;
cout << "4. Exit" << endl;
cin >> n;
switch (n) {
case 1:
insertData();
break;
case 2:
displayData();
break;
case 3:
deleteData();
break;
case 4:
exit(0);
default:
cerr << "Invalid Choice, Enter a valid choice";
}
cout << "Press 1 to continue or 0 to exit";
cin >> x;
} while (x == 1);
}
Best practices
You use the magic number 5 a lot. Give it a name so it's easier to modify if needed.
const int NUM_EMPLOYEES = 5;
There are many suggestions. Your array does not have to live at a global scope. It should not. It should be declared inside main and then passed to the functions as an argument.
Further, there is no need for it to be dynamically allocated at all. If you are going to dynamically allocate with new you'll want to remember to de-allocate with delete []. Most modern desktops OSes will automatically release that memory when your program finishes, but it's a good habit to get into.
Alternatively, you can dynamically allocate with a smart pointer and the smart pointer will handle the de-allocation for you.
auto emp = std::make_unique<emp[]>(NUM_EMPLOYEES);
Incorporating some of these ideas might look like:
int main() {
employee emp[NUM_EMPLOYEES];
insertData(emp, NUM_EMPLOYEES);
return 0;
}
You tie modifying your data very closely to the UI. These can and probably should be separated. For instance, you might have a int menu() function that prompts for a menu choice and returns it, but doesn't actually do anything to the data.
int menu() {
while (true) {
cout << "Please enter the number corresponding to an operation you want to perform\n";
cout << "1. Insert Data" << endl;
cout << "2. Display Data" << endl;
cout << "3. Delete Data" << endl;
cout << "4. Exit" << endl;
int choice = 0;
cin >> choice;
if (choice < 1 || choice > 4) {
cerr << "Invalid option." << endl;
continue;
}
return choice;
}
}
You can now use this valid menu choice to decide what to do to your data.
Because all of your functions need to accept this data, you should make your collection of employees a class/struct, and implement these functions as member functions. I suspect that's a bit beyond where you're at with C++, but object oriented programming and model-view-controller design are things to read up on.
This (out of scope) memory allocation is so wrong...
employee *emp = new employee[5];
just do it:
employee emp[5];
In your deleteData() perhaps you want to set entries to zero instead of copying from the next position (I guess this is what delete denotes). For example you may want this implementation:
void deleteData(){
int pos;
cout<<"Enter the position you want to delete Data";
cin>>pos;
if (pos<5) {
emp[pos].name = "";
emp[pos].empId = 0;
emp[pos].dept = "";
emp[pos].age = 0;
} else {
cout<<"Invalid Size please enter a size smaller than 5";
}
}
This implementation prevents the potential out-of-bound errors!

need help, C++ set operations calculator

I'm currently trying to make a set operations calculator using c++ and I am still quite new to this language, I've basically finished the code(with the help of a few friends and google ofc), but I am required to have at least five sets instead of two for every operation except the complement of a set, I don't really know how to edit this to include five sets without ruining the code, it would be great if you guys could help me, thank you so much
here's the code:
#include <iostream>
void menu ();
void unionofsets();
void intersectionofsets();
void differenceofsets();
void complementofset();
void exit ();
using namespace std;
int main (){
char ch='y';
while(ch=='y')
{
menu ();
int choice;
cout <<"Please enter the operation you want here:";
cin >>choice;
switch (choice){
case 1:
unionofsets();
break;
case 2:
intersectionofsets();
break;
case 3:
differenceofsets();
break;
case 4:
complementofset();
break;
case 5:
exit ();
break;
default :
cout <<"The system encountered some errors, please try again.......\n Thank you.";
}
cout<<"\n Do you want to continue(yes(y)/no(n))";
cin>>ch;
}
return 0;
}
void menu ()
{
cout <<"Please select an operation by entering it's corresponding number.\n";
cout <<"1.Union of Two Sets"<<endl;
cout <<"----------------------\n";
cout <<"2.Intersection of Two Sets"<<endl;
cout <<"----------------------\n";
cout <<"3.Difference of Two Sets"<<endl;
cout <<"----------------------\n";
cout <<"4.Complement of a Given Set"<<endl;
cout <<"----------------------\n";
cout <<"5.Exit the Program"<<endl;
}
void unionofsets()
{
int size1,size2;
int set1[30];
int set2[30];
cout <<"You've selected to find the Union of two sets.\n";
cout <<"Enter the number of elements in the first set:";
cin >>size1;
cout <<"Enter the number of elements in the second set:";
cin >>size2;
cout <<"Enter "<<size1 <<" elements for first set:";
for (int i=0;i<size1;i++)
{
cin >>set1[i];
}
cout <<"Enter "<<size2<<" elements for the second set:";
for (int j=0;j<size2;j++)
{
cin >>set2[j];
}
cout <<"The union of set 1 and set 2 = {";
int k;
for (int a=0;a<size1;a++)
{
cout <<set1[a]<<" ,";
}
for (int i=0;i<size2;i++)
{
for (k=0;k<size1;k++)
{
if (set2[i]==set1[k])
{
break;
}
}
if (k==size1)
{
cout<<set2[i]<<" ,";
}
}
cout <<"}";
cout<<"\n-------------------------------------------------------------------------- \n";
}
void intersectionofsets(){
int set1[20];
int set2[20];
int sizeofset1,sizeofset2;
cout <<"You've selected to find the intersection of two sets."<<endl;
cout <<"Enter the number of elements in first set:";
cin >>sizeofset1;
cout <<"Enter the number of elements in second set:";
cin >>sizeofset2;
cout <<"Enter "<<sizeofset1<<" elements for first set separated by spaces:";
cout <<endl;
for (int i=0;i<sizeofset1;i++)
{
cin>>set1[i];
}
cout <<"Now enter "<<sizeofset2<<" elements for second set precisely:";
cout <<endl;
for (int j=0;j<sizeofset2;j++)
{
cin>>set2[j];
}
cout<<"The intersection set of first and second set is :";
cout<<" { ";
for (int i=0;i<sizeofset1;i++)
{
for (int j=0;j<sizeofset2;j++)
{
if (set1[i]==set2[j])
cout <<set1[i]<<", ";
}
}
cout<<"}";
cout<<"\n-------------------------------------------------------------------------- \n";
}
void differenceofsets (){
int size1;
int size2;
int set1[34];
int set2[54];
cout <<"You've selected to find the difference of two sets.\n";
cout <<"Enter the number of elements in set1:";
cin >>size1;
cout <<"Enter the number of elements in set2:";
cin >>size2;
cout <<"Enter the elements for the first set:";
for (int i=0;i<size1;i++)
{
cin >>set1[i];
}
cout <<"Enter the elements for the second set:";
for (int k=0;k<size2;k++)
{
cin >>set2[k];
}
cout <<"The difference of two sets you have entered is {";
int l;
for (int i=0;i<size1;i++)
{
for (l=0;l<size2;l++)
{
if (set1[i]==set2[l]){
break;
}
}
if (l==size2)
cout <<set1[i]<<" ,";
}
cout<<"}";
cout<<"\n-------------------------------------------------------------------------- \n";
}
void complementofset(){
int sizefuni=30;
int sizefgiv;
int uniset[30];
int userset[30];
uniset[0]=0;
cout <<"You've selected to find the complement of a set.\n";
cout <<"The universal set for your set is suppose to be \n\n {";
for (int i=0;i<sizefuni;i++)
{
uniset[i]=uniset[0]+i;
cout <<uniset[i]<<" ,";
}
cout <<"}\n\n"<<endl;
cout<<"enter the size of set :";
cin>>sizefgiv;
cout <<"enter the element of the set to find the complement.";
for (int k=0;k<sizefgiv;k++)
{
cin >>userset[k];
}
int l;
cout <<"The complement of the given set is ={";
for (int i=0;i<sizefuni;i++)
{
for (l=0;l<sizefgiv;l++)
{
if (uniset[i]==userset[l]){
break;
}
}
if (l==sizefgiv)
cout <<uniset[i] <<" ,";
}
cout<<"}";
cout<<"\n-------------------------------------------------------------------------- \n";
}
void exit(){
cout <<"Thank you for using our software.";
}

program stopped working when I'm trying to input [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm working on a project, to create a linked list in class but I can't even start working on it because every time I run the program it's will stop working when I want to input data.
Can someone tell me how to input data properly using class? and if possible please let me know how to improve this program. The code that I've done is quite long.
I'll try to make it short and simple for you guys to understand. A lot of people been suggesting me to use std::string but our lecturer never mentioned about it so we have no idea how to use it.
If I have to use it that means I have to start learn it from the beginning which means it will take time for me to really understand it.
We're also required to have a function where we can update the data stored, search the data based on one of its data and make a summary for it.
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#include <conio.h>
#include <stdio.h>
#include <string>
using namespace std;
//CLASS USED IN PROGRAM
class carInsurance
{
private:
int total;
int customerNo;
string name;
string iCno;
char dob[10];
string nationality;
string address;
char phoneNo[15];
string email;
string occupation;
char carNo[10];
char expireDate[11];
float insuranceAmount;
char carUsage[30];
char manufacturingDate[11];
int package;
int option;
int additional;
int noCustomer[10];
public:
void add();
void presetdata();
static void deleteFunc(carInsurance noCustomer[]);
static void viewAll(carInsurance noCustomer[]);
//constructor name has to be the same as class
carInsurance(int carInsurance_total,
int carInsurance_customerNo,
string carInsurance_name,
string carInsurance_iCno,
char carInsurance_dob[10],
string carInsurance_nationality,
string carInsurance_address,
char carInsurance_phoneNo[15],
string carInsurance_email,
string carInsurance_occupation,
char carInsurance_carNo[10],
char carInsurance_expireDate[11],
float carInsurance_insuranceAmount,
char carInsurance_carUsage[30],
char carInsurance_manufacturingDate[11],
int carInsurance_package,
int carInsurance_option,
int carInsurance_additional)
{
total = carInsurance_total;
customerNo = carInsurance_customerNo;
name = carInsurance_name;
iCno = carInsurance_iCno;
dob[10] = carInsurance_dob[10];
nationality = carInsurance_nationality;
address = carInsurance_address;
phoneNo[15] = carInsurance_phoneNo[15];
email = carInsurance_email;
occupation = carInsurance_occupation;
carNo[10] = carInsurance_carNo[10];
expireDate[11] = carInsurance_expireDate[11];
insuranceAmount = carInsurance_insuranceAmount;
carUsage[30] = carInsurance_carUsage[30];
manufacturingDate[11] = carInsurance_manufacturingDate[11];
package = carInsurance_package;
option = carInsurance_option;
additional = carInsurance_additional;
} // end of constructor
carInsurance()
{ // Set all variables to null
total = 0;
customerNo = 0;
name = " ";
iCno = " ";
dob[10] = '\0';
nationality = " ";
address = " ";
phoneNo[15] = '\0';
email = " ";
occupation = " ";
carNo[10] = '\0';
expireDate[11] = '\0';
insuranceAmount = 0;
carUsage[30] = '\0';
manufacturingDate[11] = '\0';
package = 0;
option = 0;
additional = 0;
}
// SET
void setChar(char carInsurance_dob[10],
char carInsurance_phoneNo[15],
char carInsurance_carNo[10],
char carInsurance_expireDate[10],
char carInsurance_carUsage[30],
char carInsurance_manufacturingDate[10])
{dob[10] = carInsurance_dob[10];
phoneNo[15] = carInsurance_phoneNo[15];
carNo[10] = carInsurance_carNo[10];
expireDate[11] = carInsurance_expireDate[11];
carUsage[30] = carInsurance_carUsage[30];
manufacturingDate[11] = carInsurance_manufacturingDate[11];}
void setname(string carInsurance_name){name = carInsurance_name;}
void setiCno(string carInsurance_iCno){iCno = carInsurance_iCno;}
void setAddress(string carInsurance_address){address = carInsurance_address;}
void setString(string carInsurance_nationality, string carInsurance_email,string carInsurance_occupation)
{nationality = carInsurance_nationality; email = carInsurance_email; occupation = carInsurance_occupation;}
void setInt(int carInsurance_total, int carInsurance_customerNo, int carInsurance_package, int carInsurance_option, int carInsurance_additional)
{customerNo = carInsurance_customerNo; package = carInsurance_package; option = carInsurance_option; additional = carInsurance_additional;}
void setFloat (float carInsurance_insuranceAmount){insuranceAmount = carInsurance_insuranceAmount;}
// GET
string getname(){return name;}
string getiCno(){return iCno;}
string getaddress(){return address;}
string getString(){return nationality; return email; return occupation;}
int getInt(){return total; return customerNo; return package; return option; return additional;}
float getFloat(){return insuranceAmount;}
}; //end class
Here goes my main:
//function declaration
//to prevent overload run function outside
void add();
//THE MAIN FUNCTION OF PROGRAM
int main()
{
carInsurance obj; // obj is class object
carInsurance *noCustomer[10];
int choice;
while(choice != 4)
{
cout << "1. ADD, UPDATE, DELETE\n" << "2. SEARCH\n" << "3. VIEW ALL\n" << "4. SUMMARY REPORT\n" << "5. EXIT\n" << endl;
cout << "Enter your choice: ";
cin >> choice;
system("cls");
switch(choice)
{
case 1:
{
cout << "___________________________________\n";
cout << "\n\tADD/UPDATE/DELETE\n";
cout << "___________________________________\n";
cout << "\n1. ADD\n2. UPDATE\n3. DELETE\n" << endl;
cin >> choice;
system("cls");
switch(choice)
{
case 1:
{
int i;
int total = 0;
cout << "How many customer? ";
cin >> total;
for(i=0; i<total; ++i)
{
cout << "________________________________\n";
cout << "\n\tCUSTOMER NO. " << 1 + i;
cout << "\n________________________________\n";
noCustomer[i]->add(); // this is function call to input
}
break;
}
case 2:
{
int paymentID;
//cout << "UPDATE" << endl;
cout << "\nEnter the customer ID that you want to update:";
cin >> paymentID;
// function here
break;
}
case 3:
{
int paymentID;
//cout << "DELETE" << endl;
cout << "\nEnter the customer ID that you want to delete:";
cin >> paymentID;
noCustomer[10]->deleteFunc(noCustomer[10]);
break;
}
} // End of switch case for add,update,delete
system("cls");
break;
} // End of case 1
case 2:
{
cout << "___________________________\n";
cout << "\n\t SEARCH\n";
cout << "___________________________\n";
system("pause");
system("cls");
break;
}
case 3:
{ cout << "___________________________\n";
cout << "\n\tVIEW ALL\n";
cout << "___________________________\n";
obj.presetdata();
noCustomer[10]->viewAll(noCustomer[10]);
cout<<"\n";
system("pause");
system("cls");
break;
}
case 4:
{
cout << "___________________________\n";
cout << "\n\tSUMMARY REPORT\n";
cout << "___________________________\n\n";
cout << "1. Sorted by different month\n2. Sorted by different car type\n3. Sorted by different insurance" << endl;
cin >> choice;
switch(choice)
{
case 1:
{
break;
}
case 2:
{
break;
}
case 3:
{
break;
}
default:
cout << "Wrong input! Please choose again: ";
cin >> choice;
system("pause");
}
break;
}
case 5:{
cout << "___________________________\n";
cout << "\n\tTHANK YOU!\t\n";
cout << "___________________________";
exit(0); }
default:
continue;
}// End of switch case
}// End of while
return 0; //indicates success
}//End of main
I see a problem in the inner switch statement:
case 1:
{
int i;
int total = 0;
cout << "How many customer? ";
cin >> total;
for(i=0; i<total; ++i)
{
cout << "________________________________\n";
cout << "\n\tCUSTOMER NO. " << 1 + i;
cout << "\n________________________________\n";
noCustomer[i]->add(); // this is function call to input
break;
}
}
case 2:
The break operator breaks the loop, but does not prevent executing case 2: branch.
Yet another problem: re-assignment of choice. User may input 4 in any input request that will break while (choice != 4) unexpectedly. You can avoid troubles with break and re-assignments by using functions.
There is a lot of out of array bounds access by indexes that are equal to array sizes.
It is not clear what you want to reach in dob[10] = carInsurance_dob[10]; It copies 11th char. Maybe you want to copy the whole char array. Use std::string for error-free code.

Reading a txt file in C++ from a function that forces the user to enter anthore value before continuing

I want the code to read through the file that is created and if they find the same string of data for student ID, or student name it will make the user enter another value before moving on. I was able to create and store the data so that it is persistent at this point but I have yet to figure out how to make the code search through the text file and find the user entered duplicates while at the same time forcing the user enter a new value.
I am unable to think of a way to accuracy show you all the code with including the entire program
#include<iostream>
#include<fstream>
#include <cstdlib>
#include <string>
#include "student.h"
#include "course.h"
#include "session.h"
using namespace std;
void fillStudents(student arg[], int size)
{
for (int i = 0; i < size; i++)
{
cout <<"Student #"<<i+1<<endl;
cout <<"=========="<<endl;
cout <<"Enter a student ID (i.e 97626): ";
cin >>arg[i].stuID;
cout <<"Enter the first name (i.e Ryan): ";
cin >>arg[i].fname;
cout <<"Enter the last name (i.e Brown): ";
cin >>arg[i].lname;
system("CLS");
}
}
void fillCourses(course c[], int size)
{
for (int i = 0; i < size; i++)
{
cout <<"Course #"<<i+1<<endl;
cout <<"=========="<<endl;
cout <<"Enter course name (i.e Data-Structures (put - instead of spaces)): ";
cin >>c[i].CourseName;
cout <<"Enter course ID (i.e CS-230 (put - instead of spaces)): ";
cin >>c[i].CourseID;
cout <<"Enter number of credits (i.e 3): ";
cin >>c[i].numberOfCredits;
system("CLS");
}
}
string CourseN(int choice, course ch[])
{
switch(choice)
{
case 1:
return ch[0].CourseID+" "+ch[0].CourseName;
break;
case 2:
return ch[1].CourseID+" "+ch[1].CourseName;
break;
case 3:
return ch[2].CourseID+" "+ch[2].CourseName;
break;
case 4:
return ch[3].CourseID+" "+ch[3].CourseName;
break;
case 5:
return ch[4].CourseID+" "+ch[4].CourseName;
break;
case 6:
return ch[5].CourseID+" "+ch[5].CourseName;
break;
case 7:
return ch[6].CourseID+" "+ch[6].CourseName;
break;
case 8:
return ch[7].CourseID+" "+ch[7].CourseName;
break;
case 9:
return ch[8].CourseID+" "+ch[8].CourseName;
break;
case 10:
return ch[9].CourseID+" "+ch[9].CourseName;
break;
default:
cout<<"Invalid decison!! Good Bye!"<<endl;
exit(0);
}
}
int creditTotal(int sel, course ch[])
{
switch(sel)
{
case 1:
return ch[0].numberOfCredits;
break;
case 2:
return ch[1].numberOfCredits;
break;
case 3:
return ch[2].numberOfCredits;
break;
case 4:
return ch[3].numberOfCredits;
break;
case 5:
return ch[4].numberOfCredits;
break;
case 6:
return ch[5].numberOfCredits;
break;
case 7:
return ch[6].numberOfCredits;
break;
case 8:
return ch[7].numberOfCredits;
break;
case 9:
return ch[8].numberOfCredits;
break;
case 10:
return ch[9].numberOfCredits;
break;
default:
cout<<"Invalid Decision!! Good Bye!"<<endl;
exit(0);
}
}
void fillSession(student arg[], course c[], session s[])
{
int c1, c2, c3, c4;
string ch1, ch2, ch3, ch4;
string startDate, endDate;
int cr1, cr2, cr3, cr4;
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 10; j++)
{
cout<<"class #"<<j+1<<" \t\t"<<c[j].CourseID<<" \t\t"<<c[j].CourseName<<" \t\t\t"<<"Credits: "<<c[j].numberOfCredits<<"\n\n";
}
cout<<"Enter your 1st class choice: ";
cin>>c1;
ch1=CourseN(c1,c);
cout<<"Enter your 2nd class choice: ";
cin>>c2;
ch2=CourseN(c2,c);
cout<<"Enter your 3rd class choice: ";
cin>>c3;
ch3=CourseN(c3,c);
cout<<"Enter your 4th class choice: ";
cin>>c4;
ch4=CourseN(c4,c);
s[i].courseID=ch1+"\n"+ch2+"\n"+ch3+"\n"+ch4;
cout<<"Enter a start date for your classes (i.e mm/dd/yyyy): ";
cin>>startDate;
s[i].startDate=startDate;
cout<<"Enter a end date for your classes (i.e mm/dd/yyyy): ";
cin>>endDate;
s[i].endDate=endDate;
cr1=creditTotal(c1, c);
cr2=creditTotal(c2, c);
cr3=creditTotal(c3, c);
cr4=creditTotal(c4, c);
s[i].totalCredits=cr1+cr2+cr3+cr4;
c1=0;
c2=0;
c3=0;
c4=0;
system("CLS");
}
}
void display_report(student s[], course c[], session se[])
{
for (int i = 0; i < 4; i++)
{
cout<<"Student ID: "<<s[i].stuID<<"\n"<<endl;
cout<<"Student Name: "<<s[i].lname<<", "<<s[i].fname<<"\n"<<endl;
cout<<"Course IDs: \n"<<se[i].courseID<<"\n"<<endl;
cout<<"Start Date: \n"<<se[i].startDate<<"\n"<<endl;
cout<<"End Date: \n"<<se[i].endDate<<"\n"<<endl;
cout<<"Total Credits: "<<se[i].totalCredits<<"\n"<<endl;
cout<<"\n"<<endl;
}
}
This is the function that I am using to create the file and continuously store the user entered information. it is within this function that I would want to try to search for the duplicate words
/**
* Writes session data to file.
* #param {session} sess sessions array.
*/
void writeSessionsToFile(session* sess, student* stude)
{
ofstream file_out("sessions.txt", ios::app);
// for now let us just assume there'll always be just 4 sessions.
for (size_t i = 0; i < 4; ++i)
{
file_out << stude[i].lname << ", "<<stude[i].fname<<"\n";
file_out << stude[i].stuID << "\n";
file_out << sess[i].courseID << "\n";
file_out << sess[i].startDate << "\n";
file_out << sess[i].endDate << "\n";
file_out << sess[i].totalCredits << "\n";
// empty line in the end of each entry.
file_out << endl;
}
}
int main()
{
cout<<"Welcome to the CS 230 Data Structures class add program!"<<endl;
cout<<"Please follow the prompt to gain a report of your courses for the year: "<<endl<<endl;
//declare and initialize 4 students
student stu[4];
fillStudents(stu, 4);
//declare and initialize 10 courses
course courses[10];
fillCourses(courses, 10);
//assign 4 courses for each student
cout<<"Enter a class selection based on the chart above (1-10), please do not choose the same class twice: "<<endl;
cout<<"Each student goes by how their information was added"<<endl<<endl;
session sessions[4];
fillSession(stu, courses, sessions);
writeSessionsToFile(sessions, stu);
//display a report showing each student with his/her courses
//show the total number of credits for each student
cout<<"Please find your name and other important information below to see your classes and credit totals: \n\n"<<endl;
cout <<"=========="<<endl;
display_report(stu, courses, sessions);
cout <<"=========="<<endl;
// instead of system(pause), pause doesn't work on linux.
cin.get();
return 0;
}
I have searched the internet as well as this website I have found function that counts the lines of the word that I am searching for, as well as functions that does find and forces the user to enter another value but I have yet to find one that I could implement in my code that will allow me to continue with the goal I have in mind

How clear the screen and return to menu

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct student
{
string firstname;
string lastname;
int age;
string gender;
string course;
string year;
string section;
int studno;
};
int menu(int &menuChoice);
void userInfo(student user[], int size, int const track);
void listUser(student user[], int size, int const track);
int main(int argc, char** argv) {
int menuChoice;
int static track = 0;
student user[30];
do {
menu(menuChoice);
switch(menuChoice) {
case 3:
userInfo(user, 30, track);
track++;
break;
case 4:
listUser(user, 30, track);
break;
}
} while(menuChoice != 5);
return 0;
}
int menu(int &menuChoice)
{
do {
cout<< "\n\t\t==========================================="
<< "\n\t\t|\tSimple Student Record Program\t |"
<< "\n\t\t==========================================="
<< "\n\n\t\t\t\t [MAIN MENU]"
<< "\n\n\n[1] - Search Student\n[2] - Best Students\n[3] - Add New Student\n[4] - View Students\n[5] - Delete Student"
<< "\n\nEnter a choice: ";
cin>> menuChoice;
if (menuChoice>5||menuChoice<1)
{
cout<< "Please select an existing option!";
}
}
while (menuChoice>5||menuChoice<1);
return menuChoice;
}
void userInfo(student user[], int size, int const track)
{
cout<< "\n\n\t\t\t\t[Add a student]";
cout<< "\n\nEnter student's first name: ";
cin>> user[track].firstname;
cout<< "\nEnter student's last name: ";
cin>> user[track].lastname;
cout<< "\nAge: ";
cin>> user[track].age;
cout<< "\nGender: ";
cin>> user[track].gender;
cout<< "\nCourse: ";
cin>> user[track].course;
cout<< "\nYear: ";
cin>> user[track].year;
cout<< "\nSection: ";
cin>> user[track].section;
cout<< "\nStudent No.: ";
cin>> user[track].studno;
return;
}
void listUser(student user[], int size, int const track)
{
int list;
cout<< "\n\tName|||Age|||Gender|||Course|||Year|||Section|||Student No.\n";
for (list=0; list<track; list++)
{
cout<< "\n\n" << user[list].firstname <<" " << user[list].lastname <<"\t\t" << user[list].age <<"\t" << user[list].gender << "\t" << user[list].course << "\t" << user[list].year << "\t" << user[list].section << " " << user[list].studno <<"\n";
}
return;
}
My previous question was about a student record program got on hold for being broad, so, taking the advice and answers from some users there, I started to search and take action, I'll be specific this time.
So here's the whole code so far. My question is: how to clear the screen so that when you choose an option on the menu, you are then taken to that specific 'place' in the code and once you are done with that part of the program, clear the screen again and go back to the menu?
This is impossible to do with standard C++, which has no notion of a screen at all. You'd have to use a 3rd party library (e.g. the Windows API if you're on Windows). Since I assume that this is an exercise where only standard, platform-independent C++ is allowed, you cannot meet the requirement.
What I can tell you, again, is that you are not supposed to use arrays for such basic programming. Use std::vector.