the following program compiles fine, but after entering an item's name after selecting 'e' causes gdb to run, and in terminal it says segmentation fault which means im trying to enter something that doesnt exist but why?
by the way the program enters items input by the user into a structure. input() and enter() are the two functions that are causing me trouble, im not sure why.
thanks.
by the way the program enters items input by the user into a structure. input() and enter() are the two functions that are causing me trouble, im not sure why.
thanks.
Code:
#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdlib>
using namespace std;
const int SIZE = 10;
struct inventory{
char item[40];
double cost;
int retail;
int on_hand;
int lead_time;
}invntry[SIZE];
void init_list(), enter(), display();
void update(), input(int i);
int menu();
int main () {
char choice;
init_list();
for(;;){
choice = menu();
switch(choice){
case 'e': enter();
break;
case 'd': display();
break;
case 'u': update();
break;
case 'q': return 0;
}
}
return 0;
}
// initialize a list
void init_list(){
int t;
// makes that element empty.
for(t=0; t < SIZE;t++)
*invntry[t].item = '\0';
}
// get a menu selection
int menu(){
char ch;
cout << '\n';
do{
cout << "(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\n\n";
cout << "Choose one: ";
cin >> ch;
}while(!strchr("eduq", tolower(ch)));
return tolower(ch);
}
//input the information
void input(int i){
//enter the information
cout << "Item: ";
cin >> invntry[i].item;
cout << "Cost: ";
cin >> invntry[i].cost;
cout << "Retail: ";
cin >> invntry[i].retail;
cout << "On hand: ";
cin >> invntry[i].on_hand;
cout << "Lead time to resupply(in days): ";
cin >> invntry[i].lead_time;
}
// enters items into the list
void enter(){
int i;
// finds a free structure
for(int i = 0; i < SIZE; i++)
if(!*invntry[i].item)break;
if(i == SIZE){
cout << "List Full\n";
return;
}
input(i);
}
// modify an existing item
void update(){
int i;
char name[80];
cout << "Enter item: ";
cin >> name;
for(i = 0; i < SIZE; i++)
if(!strcmp(name, invntry[i].item))break;
if(i == SIZE){
cout << "Item not found";
return;
}
input(i);
}
void display(){
int t;
for(t = 0; t < SIZE; t++){
if(*invntry[t].item){
cout << invntry[t].item << '\n';
cout << "Cost $" << invntry[t].cost << '\n';
cout << "Retail Price $" << invntry[t].retail;
cout << "on hand: " << invntry[t].on_hand;
cout << "\nResupply time: ";
cout << invntry[t].lead_time << " days\n\n";
}
}
}