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)--;
}
}
}
Related
I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}
I'm in an Intro to C++ class, and for one of our assignments we're making an online shop. One of our problems is to make a search function for the inventory, using a linear search, then display the corresponding price, stock, and shipability for that item.
For some reason, no matter how much I try and tweak it, it always returns false for the search, and that the store doesn't carry the item, even if I type in an item that I know is in the items array.
For example, if I type Moon Pie (which is in my array) in the getline, it'll still return as -1 like it isn't. Anything noticeably wrong with this code?
Here's my inputInventory.txt
Moon Pie 3.50 15 1
Cosmic Brownie 2.00 12 0
Moon Shine 7.00 7 1
Astronaut Icecream 4.00 11 1
Neptune Nuggets 2.50 30 1
Venus Vodka 6.50 10 1
Planet Pop 4.50 20 0
Starry Salad 3.00 15 0
Celeste Cakes 5.00 11 1
Plasma Potion 9.99 4 1
Star Fruit 2.50 10 1
Sun-dae 7.00 20 0
Moon Cheese 5.00 10 1
Milky Way Milkshake 6.50 5 0
Pluto Pie 7.00 9 10
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 15;
void searchInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]);
int linearSearch(string arr[], int size, string value);
int main() {
int input;
string items[MAX];
double priceItems[MAX];
int noItems[MAX][2];
cout << "\n1. Read in Inventory\n";
cout << "2. Display Inventory\n";
cin >> input;
while (input > 2 || input < 1) {
cout << "An error has occured. Please input a value 1 - 2. >> ";
cin >> input;
}
switch (input) {
case 1:
if (readInventory(items, priceItems, noItems) == true) {
cout << "\nReading the file...\n";
}
break;
case 2:
searchInventory(items, priceItems, noItems);
break;
}
}
bool readInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]) {
bool fileRead = false;
ifstream inputFile; // Pointer
inputFile.open("inputInventory.txt");
if (inputFile) // Test if file opened
{
for (int row = 0; row < MAX; row++) {
getline(inputFile, itemNames[row], '\t');
inputFile >> itemCost[row];
inputFile >> itemNoShip[row][0];
inputFile >> itemNoShip[row][1];
}
fileRead = true;
inputFile.close();
}
return fileRead;
}
void searchInventory(string itemNames[], double itemCost[], int itemNoShip[MAX][2]) {
string search;
int result;
int position;
cout << "Please type the name of the item you are looking for. > ";
cin.ignore();
getline(cin,search);
result = linearSearch(itemNames, MAX, search);
cout << result;
if (result >= 0) {
cout << "\nYour item was found!\n";
cout << itemNames[result] << itemCost[result] << itemNoShip[result][0] << "Shippable:" << itemNoShip[result][1];
}
else {
cout << "\nThis item was not found in the list.";
}
}
int linearSearch(string arr[], int size, string value) {
int position;
int index;
for (index = 0; index < size; index++) {
if (arr[index] == value) {
position = index;
}
else {
position = -1;
}
}
return position;
}
for (index = 0; index < size; index++)
if (arr[index] == value) {
position = index;
}
else {
position = -1;
}
This loop continually overwrites position.
Unless your sought-after element is the last one in the array, immediately after it's been found the next element will cause position to be set to -1 again (unless that one matches too 😋).
You should stop looping (or, at least, stop updating position) as soon as a match is found.
Also, it would be advisable to wrap the entire loop body in {} braces, as that is conventional and what people will expect to see, making the code easier to read and to understand.
How about:
int linearSearch(string arr[], int size, string value)
{
for (int index = 0; index < size; index++)
{
if (arr[index] == value)
return index;
}
return -1;
}
You should break out of the for loop once you found the item, if not the loop will just continue and overwrite position. Edited: Based on PaulMcKenzie's comment, you should initialize position with a value so that it will not return garbage value.
int linearSearch(string arr[], int size, string value) {
int position = -1;
int index;
for (index = 0; index < size; index++) {
if (arr[index] == value) {
position = index;
break;
}
}
return position;
}
The problem is cin.ignore(), since the default value of the first parameter is one, the first letter will always be taken out. So if someone typed "Moon Pie", the value in search will be "oon Pie".
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}
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
I am having trouble debugging this code so it reads two columns from the file and when the first column (Department is the same it just adds the second column to the old dept already created)This code is having trouble with looping. Any walk through, help would be much appreciated ! Thanks.
#include <iostream>
#include <fstream>
using namespace std;
ifstream inputFile; //stream object
int main()
{
inputFile.open("text.txt");
const int SIZE = 15;
int candy[SIZE];
int dept[SIZE];
int valuecounter = 0;
int Candy;
int Department;
while (inputFile >> Department >> Candy)
{
// Exit loop if we have filled the entire array
if (valuecounter == SIZE)
break;
// Update previous values
for (int index = 0; index < valuecounter; index++)
{
if (dept[index] == Department)
{
candy[index] += Candy;
}
}
// Update current values and increment counter
dept[valuecounter] = Department;
candy[valuecounter] = Candy;
valuecounter++;
}
for (int i = 0; i < valuecounter ; i++)
cout << dept[i] << " " << candy[i] << endl;
inputFile.close();
return 0;
}
and the list of input being for ex:
910 8
450 9
750 10
150 35
750 19
150 18
910 19
390 19
520 6
110 78
300 23
110 1
110 5
120 6
150 16
300 23
110 1
110 5
120 6
150 16
the array should be partially filled. but it produces weird outcome! logic error?
You have initialized valuecounter, and all elements of array dept, to zero. For this reason, in every iteration of the while loop, condition dept[valuecounter] == NULL will always evaluate to true. This means that, in every iteration, only code in the first if statement will execute.
Note that this is not the only problem with this code. As user Crazy Eddie pointed out, using NULL as an integer is considered very bad practice.
EDIT:
Replace your while loop with the following:
while (inputFile >> Department >> Candy)
{
// If this Department already exists ...
for (int index = 0; index < valuecounter; index++)
{
if (dept[index] == Department)
{
// ... update the corresponding value in 'candy' and continue the loop
candy[index] += Candy;
continue;
}
}
// If this Department does not exist, and if there are are more
// available array elements, assign a new Department
if (valuecounter < SIZE)
{
dept[valuecounter] = Department;
candy[valuecounter] = Candy;
valuecounter++;
}
}
int main()
{
const int SIZE = 15;
int candy[SIZE];
int dept[SIZE];
int valuecounter = 0;
int Candy;
int Department;
inputFile.open("text.txt");
if (!inputFile)
{
cout << "\nError opening file" << endl
<< "Exiting\n" << endl;
exit(1);
}
while (valuecounter < SIZE && inputFile >> Department >> Candy)
{
//setting bool to false everytime loop starts over.
bool found = false;
for (int index = 0; index < valuecounter; index++)
{
if (dept[index] == Department)
{
candy[index] += Candy;
//setting bool to true if department found
found = true;
}
}
if (!found)
{
dept[valuecounter] = Department;
candy[valuecounter] = Candy;
valuecounter++;
}
}
inputFile.close();
if (valuecounter == 0)
{
cout << "\n\nEMPTY FILE\nExiting.\n\n" << endl;
exit(1);
}
here i had three different functions do different things with data
return 0;
}
basically what i was missing is to set bool back to false whenever while loop started over this is why data wasn't calculated properly. Anyways Thank you all for help and all the tips!