Attached Image Someone Please help me fix the this problem.I was using the if statement to determine the material is copper, and then I would like to use arrays to print out different type of length and material. Thank You.
enter code here
#include <stdlib.h>
#include <iostream>
using namespace std;
float steelbar ();
float steelrod ();
char printMenu ();
void testing(float length, float area, float stress, float price);
int main()
{
char Choice;
float result;
cout<<"\t\tWelcome to Smart Calculating System\n";
cout<<"\t\t_______________________________________\n";
Choice = printMenu();
if (Choice == 'A' || Choice == 'a')
{
result = steelbar();
}
else if (Choice == 'B' || Choice == 'b')
{
result = steelrod();
}
else
{
printf("Invalid input!\n");
fflush(stdin);
getchar();
}
}
char printMenu ()
{
char choice;
cout<<" Please choose a type:\n";
cout<<" A/a = Steel bar B/b = Steel rod\n";
cout<<"Answer = "<<endl;
cin>>choice;
cout<<"\n";
return choice;
}
/////////////////////////////////////////////////////////////////
float steelbar ()
{
float length, width, height, pressure, area, stress, price;
int program=1;
while(program == 1)
{
cout<<"Please enter length: "<<endl;
cin>>length;
cout<<"Please enter width: "<<endl;
cin>>width;
cout<<"Please enter height: "<<endl;
cin>>height;
cout<<"Please enter pressure: "<<endl;
cin>>pressure;
area = height * width;
stress = pressure / area;
cout<<"\nThe stress is : "<<stress<<endl;
if (stress <= 690)
{
testing(length, area, stress, price);
fflush(stdin);
getchar();
cout<<"\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = ";
cin>>program;
if (program == 1)
{
printMenu ();
}
else (program == 0);
{
return 0;
}
}
else if (stress > 690)
{
cout<<"\n";
cout<<" Please enter stress less than 690 MPA\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = "<<endl;
system("cls");
}}
return price;
}
/////////////////////////////////////////////////////////////////
float steelrod ( )
{
float length, diameter, pressure, area, stress, price ,density, rate ;
int program;
while(program == 1)
{ cout<<"Please enter length: "<<endl;
cin>>length;
cout<<"Please enter diameter: "<<endl;
cin>>diameter;
cout<<"Please enter pressure: "<<endl;
cin>>pressure;
area = (3.14159 * diameter * diameter) / 4;
stress = pressure / area;
cout<<" The stress is : "<<stress;if (stress <= 690)
{
testing(length, area, stress,price);
fflush(stdin);
getchar();
system("cls");
cout<<"\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = ";
cin>>program;
if (program == 1)
{ system("cls");
main ();
}
else (program == 0);
{return 0;
}
}
else if (stress > 690)
{
cout<<"\n";
cout<<" Please enter stress less than 690 MPA\n";
cout<<" Do you wish to continue? (Yes=1 /No=0)\n";
cout<<"Answer = "<<endl;
cin>>program;
system("cls");
}
return price;
}
}
/////////////////////////////////////////////////////////////////
void testing(float length, float area, float stress, float price)
{
const char *material[30];
int i, j;
if( stress <= 70)
{
material[i] = "Copper";
price = length * area * 10 * 1.5;
}
else if( stress >70 && stress <= 130 )
{
material[i] = "Cast iron";
price = length * area * 15 * 1.8;
}
else if( stress >130 && stress <= 200 )
{
material[i] = "Brass";
price = length * area * 17 * 2.0;
}
else if( stress >200 && stress <= 690 )
{
material[i] = "ASTM A51";
price = length * area * 22.5 * 2.20;
}
for(i=0;i<3;i++)
{
cout<<"Material : "<<material[i];
cout<<"\nThe total price is : RM"<<price<<endl;
}
}
I'm not sure about your intent but... I see sime things that are very strange.
(1) in testing(), you define the variable i but you don't assign any value to it; so, when you assign
material[i] = "Cooper";
the value for i is undefined
(2) in printarray(), you definition of material is
float material[i], price;
where i is a parameter of the function (with undefined value, if received from testing()); this isn't standard C++ because you can't define a C-style array (but was your intention?) with a not-known at compile time dimension
(3) in printarray() you define material as a float array of size i and you don't initialize the i values; so material carry i undefined values; when you acess it in the following for
for(i=0;i<3;i++)
{
cout<<"Material : "<<material[i];
cout<<"\nThe total price is : RM"<<price<<endl;
}
you access 3 undefined values
(4) according the image you report us, with
cout<<"Material : "<<material[i];
you print a C-style string (char *) with values "Cooper", some garbage (uninitialized values) and empty string; according the code you show us, material should be an array of float. I deduce that the image you show us is generated by a different code. Please, show us the corrispondent (and complete) code
(5) sorry for my bad English
Related
I am currently writing a program for a class involving code for a Grade Point Average calculator with added features. My code was working right up until I added my last line of code for the sum of the grades and subsequent division for the average. I feel like I'm missing something obvious here, but I'm at a loss, currently. Ideally, this program would be accepting input from a user at four separate points, adding the input together, and then dividing it by 4 (as the current number of grades I have code for is 4, but I plan on increasing this amount once I figure out how to solve this issue).
Initially, I was getting errors because I was asking the code to translate a double variable into a char variable and then back into a double variable (error code C4244). I also changed the end of the code to declare the sum of all grades as a separate variable, because including it all in one variable, GPA, resulted in the program outputting a seemingly random number. I since changed my code to flow more evenly, however now when I execute the program, it asks for the initial input for the first grade then skips right over the second, third, and fourth grades.
I'm still extremely new to C++, so I may be over complicating my code, but I'm stumped.
#include <iostream>
using namespace std;
int GPAAndHonorsCalculator;
int main()
{
//Declaring initial values
double A = 4.0;
double B = 3.0;
double C = 2.0;
double D = 1.0;
double F = 0.0;
double GPA = 0.0;
//Created if else statements to handle user input and translation into data for the program to use.
cout << "Please enter your first grade: " << endl;
double gradeOne = 0.0;
cin >> gradeOne;
if (gradeOne == 'A') {
gradeOne = 4.0;
}
else if (gradeOne == 'B') {
gradeOne = 3.0;
}
else if (gradeOne == 'C') {
gradeOne = 2.0;
}
else if (gradeOne == 'D') {
gradeOne = 1.0;
}
else if (gradeOne == 'F') {
gradeOne = 0.0;
}
cout << "Please enter your second grade: " << endl;
double gradeTwo = 0.0;
cin >> gradeTwo;
if (gradeTwo == 'A') {
gradeTwo = 4.0;
}
else if (gradeTwo == 'B') {
gradeTwo = 3.0;
}
else if (gradeTwo == 'C') {
gradeTwo = 2.0;
}
else if (gradeTwo == 'D') {
gradeTwo = 1.0;
}
else if (gradeTwo == 'F') {
gradeTwo = 0.0;
}
cout << "Please enter your third grade: " << endl;
double gradeThree = 0.0;
cin >> gradeThree;
if (gradeThree == 'A') {
gradeThree = 4.0;
}
else if (gradeThree == 'B') {
gradeThree = 3.0;
}
else if (gradeThree == 'C') {
gradeThree = 2.0;
}
else if (gradeThree == 'D') {
gradeThree = 1.0;
}
else if (gradeThree == 'F') {
gradeThree = 0.0;
}
cout << "Please enter your fourth grade: " << endl;
double gradeFour = 0.0;
cin >> gradeFour;
if (gradeFour == 'A') {
gradeFour = 4.0;
}
else if (gradeFour == 'B') {
gradeFour = 3.0;
}
else if (gradeFour == 'C') {
gradeFour = 2.0;
}
else if (gradeFour == 'D') {
gradeFour = 1.0;
}
else if (gradeFour == 'F') {
gradeFour = 0.0;
}
int gradeSum = gradeOne + gradeTwo + gradeThree + gradeFour;
GPA = gradeSum / 4;
cout << GPA;
}
At the suggestion of #LukeH, I cleaned up my code and made a nested while switch statement. Here is part of the working code:
int main() {
//Declaring initial values, as well as initializing a counter for later loop.
int gradeValue = 0;
int gradeCount = 0;
char userGrade = 0;
double GPA = 0.0;
//Creating while loop with switch statement nested inside to handle large amounts of repeating code.
while (gradeCount!= 4) {
cout << "Please enter a grade (A, B, C, D, or F): ";
cin >> userGrade;
switch (userGrade) {
case 'A': {
gradeValue = gradeValue + 4;
++gradeCount;
break;
}
I repeated this process for each grade and it worked a treat!
I commented earlier, but I figured I'd elaborate a bit more if it could help further.
As it seems you have already figured out, you were trying to store a character in a double variable which will either break your code or have some serious unexpected results. Unlike languages like Javascript, variables in C++ have a defined type and cannot change between, say, a double and a string. In your edited code you seemed to have accounted for this and it seems your code is now functioning better.
One important thing to note, especially as it seems you are still learning, is there should be a little internal alarm that goes off in your head as a programmer anytime you are writing blocks of code that are the same or very similar to code you have already written. The saying "DRY" or "Don't Repeat Yourself" is very popular for a reason and can help your code be much easier to read, write, and edit.
For your example, the main function has all of your logic in it and as it gets longer and longer it can be hard to interpret what is happening in the written code. Your code is roughly:
int main() {
//Declaring initial values, as well as initializing a counter for later loop.
int gradeValue = 0;
int gradeCount = 0;
char userGrade = 0;
double GPA = 0.0;
//Creating while loop with switch statement nested inside to handle large amounts of repeating code.
while (gradeCount!= 4) {
cout << "Please enter a grade (A, B, C, D, or F): ";
cin >> userGrade;
switch (userGrade) {
case 'A': {
gradeValue = gradeValue + 4;
++gradeCount;
break;
}
case 'B': {
gradeValue = gradeValue + 3;
++gradeCount;
break;
}
case 'C': {
gradeValue = gradeValue + 2;
++gradeCount;
break;
}
case 'D': {
gradeValue = gradeValue + 1;
++gradeCount;
break;
}
case 'F': {
++gradeCount; // no need to add to value since F=0
break;
}
}
// logic to display GPA
// TODO
If you instead put the user input logic in its own function, your main() will be much cleaner. An added benefit is that if you need to update the logic for getting input (like you did once already!), your main() function doesn't need to change at all.
Your main() would look something like this then:
int main() {
// declare variables
double gradeValue = 0.0;
int gradeCount = 0;
// get input
while(gradeCount < 4) {
gradeValue += getUserGrade(); // add grade to GPA
gradecount++;
}
// logic to display GPA
// TODO
}
Much easier to understand right? In your getUserGrade() function you would just need to have your switch statement logic and return a double value of the grade they input. I left out the logic to display GPA just because this is an assignment and that part is up to you to finish.
With this simpler framework in place, you can easily adjust the code to be able to handle as many grade inputs as the user wants to give. If you just have an option for the user to type "done" or something else significant when they are asked for a grade, you can return a special value that your code in main() can use to know when to stop taking input (-1.0 would work because that would not be a valid GPA). Your main() would look something like this then:
int main() {
// declare variables
double gradeValue = 0.0;
int gradeCount = 0;
// get input
while(true) {
double usrInput = getUserGrade();
if(usrInput == -1.0) break; // exit loop if user is done
gradeValue += usrInput;
gradecount++;
}
// logic to display GPA
// TODO
}
With only changing a few lines of code, you can now have a program that is much more flexible!
Firstly, what are you using the variables A, B,C, D, F for? Secondly you can't use double type variable to store characters. Just use a char variable to get the input grade and set the grade variable accordingly. Also if you plan to add more of these grades, then it will be better for you to either write it in a function and call it again and again(or put the function call in a loop) so that repetition of code is avoided and the code in general looks cleaner.
I'm creating a software in C++ loops on one function(double) indefinitely. After going through the loop the first time, the second time it runs, it returns 'nan'. Where did I go wrong.
int main()
{
double Balance = 100;
for (int i = 0; i < 5; i++) {
nyaradzo(Balance, i);
}
}
double nyaradzo(double bal, int pass)
{
int x = bal;
double Amount;
string policy_number;
double confirmation;
cout<<"WELCOME TO NYARADZO ONLINE POLICY PAYMENT"<<endl;
cout<<"ENTER YOUR POLICY NUMBER"<<endl;
cin>>policy_number;
cout<<"ENTER AMOUNT YOU WISH TO PAY FOR YOU POLICY"<<endl;
cin>>Amount;
cout<<"YOUR POLICY NUMBER IS: "<<policy_number<<endl;
cout<<"YOU HAVE CHOSEN TO PAY $"<<Amount<<" FOR YOUR FUNERAL POLICY. \n Is this information correct?"<<endl;
cout<<"1 TO CONFIRM"<<endl;
cout<<"2 TO CANCEL"<<endl;
cin>>confirmation;
if (confirmation==1) {
if (Amount <= x) {
x -= Amount;
cout<<"Transaction Complete"<<endl;
cout<<"YOUR BALANCE IS $"<<x<<endl;
return x;
}
else if (Amount > x) {
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"You cannot withdraw more than your actual balance..."<<endl;
return 0;
}
else {
cout <<x << endl;
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"Your purchase must be greater than or at least equal to $1"<<endl;
return 0;
}
}
else if (confirmation==2) {
cout<<"YOU HAVE CHOSEN TO CANCEL YOUR ZESA TRANSACTION"<<endl;
// transaction(bal, pass);
}
else
{
cout << "Invalid selection" << endl;
return 0;
}
}
When it goes through the loop a second time, it fails.
Not all paths in nyaradzo return a value. You should enable all your compiler warnings. It should alert you of this. Since x = bal and you only modify x when the amout is ok, add this as the final line of the func:
return x;
And change type of x to double. Or get rid of x and use bal throughout.
Also, I assume you want to keep a running balance. Then you should change the for loop to:
for (int i = 0; i < 5; i++) {
Balance = nyaradzo(Balance, i);
}
My Basic Algorithm:
Ask for input money amount; Rolls two 6-sided dice; if they add up to 7, add 4 to money amount; else, subtract 1 from money amount; loop until moneyamount<0; loop game user says n when prompted to play again.
/*
*File: hw3
*Author: Nathaniel Goodhue
*
*Created on: 9/15/15
*Description: Game of lucky sevens
*
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
srand (time(NULL));
double moneyAmount;
int winValue = 7;
int numRolls = 0;
char playAgain = 'y';
while(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
while(moneyAmount>0)
{
int roll1= (rand()%6)+1;
int roll2 = (rand()%6)+1;
if(roll1+roll2 == winValue)
{
moneyAmount+=4;
numRolls++;
}
else
{
moneyAmount-=1;
numRolls++;
}
}
cout<<"It took "<<numRolls<<" roll(s) to lose all of your money"<<endl;
// cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
cout<<"Play again? y/n"<<endl;
cin>>playAgain;
if(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
numRolls = 0;
}
else
{
break;
}
}
return 0;
}
Above is my current code. It works as intended. What I am stuck on is that I need to be able to implement this line of code right after money drops below 0:
cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
I need to find out when there was the most money and after how many rolls that it appeared. The maxAmount variable would be the max amount of money achieved, and the maxRolls variable would be the number of rolls when maxAmount was reached.
This is pretty simple to add to your code. What you can do is check if the amount of money they have is greater than the max amount of money. If it is then set max to current and record the number of turns it took to get that value.
int maxAmount = moneyAmount, maxRolls = 0;
while(moneyAmount > 0)
{
int roll1 = (rand() % 6) + 1;
int roll2 = (rand() % 6) + 1;
numRolls++;
if(roll1 + roll2 == winValue)
moneyAmount += 4;
else
moneyAmount -= 1;
if (moneyAmount > maxAmount)
{
// the current amount of money is greater than the max so set max to current and get the number of rolls
maxAmount = moneyAmount;
maxRolls = numRolls;
}
}
How can I accept and average positive numbers? When a negative number is entered, it should terminate the loop and display the average (excluding the negative number).
#include <iostream>
using namespace std ;
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
if(x<0) {
sum+=x;
counter++;
continue;
} else if (x>0) {
cin>>x;
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
#include <iostream>
using namespace std;
int main() {
int sum = 0, count = 0, input; // initialize all variables
while (true) { // loop forever (until break is reached below)
cin >> input; // get user input
if (input < 0) break; // if it's negative, exit loop
sum += input; // otherwise add it to the running sum
count++; // increase the count by 1
}
if (count > 0) cout << (double)sum / count; // if we have at least one number, display avg
else cout << "No numbers to average" << endl; // else complain.
return 0;
}
Note that this will fail if the user provides bad input. If you need it to handle bad input, see here about cin types.
The implementation that you have immediately adds the input to your sum.
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
cin >> x;
if (x>0) {
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
This would allow you to check the input before adding to your total.
It is also important to mention to avoid dividing by zero if the user's first input is a negative number.
here is an improved version, that checks if loop exist without any positive integers entered to avoid divide by zero error
#include <iostream>
using namespace std ;
int main () {
int x;
float counter=0,sum;
float avg;
bool isPositive = true;
while ( isPositive) {
cin>>x;
if(x>0)
{
sum+=x;
counter ++;
}
else {
isPositive = false;
}
}
// if we divide by zero, an error will occur
if(counter > 0)
{
avg=(float)(sum/counter);
cout<<avg<<endl;
}
else cout << "Please enter positive numbers";
return 0 ;
}
I have a program used to manage a database of records called "client_DB". The array "client_DB" is composed of customer cell phone call records. Each customer call record contains eight fields, which are as follows: 1) a ten digit cell phone number (string, no dashes), 2) the number of relay stations used in making the call (integer), 3) the length of the call in minutes (integer), 4) the net cost of the call (double), 5) the tax rate (double), 6) the call tax (double), 7) the total cost of the call (double) and 8) string field called "discount_aval with a value of "yes" or "no". The array client_DB has a capacity (SIZE) of 20 records.
It reads from an input file first called "client_data.txt" which is composed of these values:
9546321555 0 0 yes
5612971340 5 50 no
3051234567 8 25 no
7542346622 24 17 no
3054432762 15 30 yes
9544321011 50 100 yes
8776219988 87 82 yes
9042224556 4 5 yes
7877176590 11 1 no
5617278899 20 45 no
9546321555 4 3 yes
5612971340 79 86 no
3051234567 8 25 no
7542346622 24 118 no
3054432762 115 25 yes
9544321011 43 10 yes
8776219988 265 22 yes
9042224556 2 5 yes
7877176590 89 67 no
5617278899 40 56 no
My Remove function only removes the first value, if i type in to remove any other value, it simply wont! My Search function simply gives me back 2 numbers. Which is off and its not what i want. Help? I want to be able to ask the user for a cellnumber, then have it search the entire array and find it and delete it. I want my search grab an input also, find it and give me back its location. I tried but i dont know what i did wrong. In my main, i called both functions when the user selects it from the function Menu.
heres my code:
#include <iostream>
#include <string>
#include <fstream>
//************************************************************************
//Name: Kevin Due Date: 022113
//Instructor: Dr. Bullard Total Points: 100 pts
//Assignment2: client_call.cpp UsIDFAU:
//:
using namespace std;
const int CAPACITY = 20;
class client_db
{
public:
string cellnum;
int numofrelay;
int call_length;
double net_cost;
double tax_rate;
double call_tax;
double total_cost;
string discount_aval;
};
bool IsFull(int); //returns true if the array is full; otherwise false.
bool IsEmpty(int count);// returns ture if the array is empty; otherwise false.
void Add(client_db A[], int & count, client_db & db);
void Remove(client_db A[], int *count, string name);// removes an item from the array if it is there
void Print_DB(client_db A[], int count);//prints to output file
void Call_stats(client_db A[], int count);// prints all the items in the array
int Search_DB(client_db A[], int count, string name); //if the name is in the array, its location is returned
// //otherwise return -1;
//
bool IsFull(int count)
////Description: Determines if the array is full
{
return (count == CAPACITY);
}
bool IsEmpty(int count)
////Description: Determines if the array is empty
{
return (count == 0);
}
void Process (client_db A[], int count)
{
for(int i=0; i<count; i++)
{
if (A[i].numofrelay >=1 && A[i].numofrelay<=5)
{
A[i].tax_rate=0.01;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay >=6 && A[i].numofrelay<=11)
{
A[i].tax_rate=0.03;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay>=12 && A[i].numofrelay<=20)
{
A[i].tax_rate=0.05;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].numofrelay);
}
else if (A[i].numofrelay >=21 && A[i].numofrelay<=50)
{
A[i].tax_rate =0.08;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay >50)
{
A[i].tax_rate =0.12;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
A[i].call_tax = ((A[i].tax_rate)/(100))*(A[i].net_cost);
A[i].total_cost = A[i].net_cost + A[i].call_tax;
}
}
void Print_DB(client_db A[], int count)
//Description: Prints the items stored in A to the standard i/o device
{
string filename;
cout<<"Enter output filename: "; //geting filename
cin>>filename;
ofstream output; //declaring an output file stream
output.open(filename.c_str()); // c_str() converts a C++ string into a
// c-style string (char array) &
//open binds an ofstream to a file
for(int i=0; i<count; i++)
{
output<<A[i].cellnum<<"\t"
<<A[i].numofrelay<<"\t"
<<A[i].call_length<<"\t"
<<A[i].net_cost<<"\t"
<<A[i].tax_rate<<"\t"
<<A[i].call_tax<<"\t"
<<A[i].total_cost<<"\t"
<<A[i].discount_aval<<endl;
}
output.close();
}
int Search(client_db A[], int count, string cellnum)
////Description: Locates cellnumbers in A's fields
{
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
for(int i=0; i<count; i++)
{
if (cellnum == A[i].cellnum)
{
cout<<i<<endl;
}
}
return -1;
}
void Add(client_db A[], int &count)
////Description: Adds key to the array
{
if (!IsFull(count))
{
cout<<"Enter a cellphone number, number of relay stations and the call lenght and if a discount is available: ";
cin>>A[count].cellnum>>A[count].numofrelay>>A[count].call_length>>A[count].discount_aval;
count++;
}
else
{
cout<<"The list is full\n";
}
}
void Add(client_db A[], int &count, client_db &db)
////Description: Adds key to the array
{
if (!IsFull(count))
{
A[count] = db;
count++;
}
else
{
cout<<"The list is FULL! \n";
}
}
void Remove(client_db A[], int *count, string cellnum )
////Description: Removes the number from the array is it is there
{
int loc = Search(A,*count,cellnum);
if (IsEmpty(*count))
{
cout<<"There is nothing to remove\n";
return;
}
else if (loc == -1)
{
cout<<"Number is not in data\n";
}
else
{
for(int j=loc; j<(*count)-1; j++)
{
A[j] = A[j+1];
}
(*count)--;
}
}
void Call_stats(client_db A[],int count) // prints to screen
{
for(int i=0; i<count; i++)
{
cout<<A[i].cellnum<<"\t"
<<A[i].numofrelay<<"\t"
<<A[i].call_length<<"\t"
<<A[i].discount_aval<<endl;
}
}
void Menu ()
{
cout<<"The values of the filename you entered have been recognized"<<endl;
cout<<"Please enter the letter of your application of choice"<<endl;
cout<<" "<<endl;
cout<<"************ WELCOME TO THE MAIN MENU ************"<<endl;
cout<<" Add an item...........................A"<<endl;
cout<<" Remove an item........................R"<<endl;
cout<<" Search for an item....................S"<<endl;
cout<<" Print current data....................P"<<endl;
cout<<" Print to output file..................O"<<endl;
cout<<"****************************************************"<<endl;
}
int main()
{
char answer;
char answer2;
client_db CLIENT[CAPACITY]; //declaring database
int count = 0; //initializing count
string cellnum;
string filename;
cout<<"Hello!, this program holds clients call data records."<<endl;
cout<<"Enter input filename: "; //geting filename
cin>>filename;
ifstream input; //declaring an input file stream
input.open(filename.c_str()); // c_str() converts a C++ string into
while(count<CAPACITY && !input.eof()) //reading until the end of the file (eof=end-of-file)
{
input>>CLIENT[count].cellnum
>>CLIENT[count].numofrelay
>>CLIENT[count].call_length
>>CLIENT[count].discount_aval;
count++;
}
do
{
Menu();
cout<<"Please enter a command letter: "<<endl;
cin>>answer;
client_db db;
switch (answer)
{
case 'A' :
cout<<"Enter a cellphone number, number of relay stations and the call lenght and if a discount is available: "<<endl;
cin>>db.cellnum>>db.numofrelay>>db.call_length>>db.discount_aval;
Add(CLIENT, count, db);
break;
case 'R' : Remove(CLIENT,&count,cellnum);
break;
case 'S' :
Search(CLIENT,count,cellnum);
break;
case 'P' : Call_stats(CLIENT,count);
break;
case 'O' :
Process(CLIENT,count); //how do i set the precision for this?
Print_DB(CLIENT,count);
break;
}
cout<<"Would you like to make another command?(y/n): "<<endl;
cin>>answer2;
} while (answer2 == 'Y' || answer2 == 'y');
cout<<"Goodbye"<<endl;
return 0;
}
That seems to be exactly what you want the function to return. Note that the phone number at index 2 and 12 are the same. If fact, it seems that are only 10 unique phone numbers in the list. Therefore, you will get 2 numbers as output when searching for each of those 10 numbers, since they all have one duplicate.
If you only want the first match to be printed, simply add a break; as follows:
for(int i=0; i<count; i++)
{
if (!(A[i].cellnum.compare(cellnum)))
{
cout<<i<<endl;
break;
}
}
in the Search function. If identical phone number are not desired, you could consider checking this before allowing the user to search for a phone number.
EDIT:
I see that your Remove function is not working properly either. You try to get the index of the phone number by using the Search function, but the search function always returns -1.
I would add the break as I mentioned above, and then return i instead of -1. Declare i outside of the for loop for this to work.
As you want all occurrences to be deleted upon choosing Remove, I would do the following:
In your main function:
case 'R' :
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
Remove(CLIENT,&count,cellnum); break;
and
case 'S' :
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
Search(CLIENT,count,cellnum); break;
Search:
int Search(client_db A[], int count, string cellnum){
int index = -1;
for(int i=0; i<count; i++)
{
if (!(A[i].cellnum.compare(cellnum)))
{
cout<<i<<endl;
index = i;
break;
}
}
return index;
}
And Remove:
void Remove(client_db A[], int *count, string cellnum ){
int loc;
while((loc=Search(A,*count,cellnum)) != -1){
if (IsEmpty(*count)){
cout<<"There is nothing to remove\n";
return;
}
else if (loc == -1){
cout<<"Number is not in data\n";
}
else{
for(int j=loc; j<(*count)-1; j++)
{
A[j] = A[j+1];
}
(*count)--;
}
}
}