c++ Not able to add an element in the array [closed] - c++

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 7 years ago.
Improve this question
I am fairly new to c++. I am trying to add another element in the array. The function should change the array and the number of items in the array after the addEntry function is completed, but it doesn't. If I use the display function to show the array, only the original array is shown. Please help.
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE = 10; // total size of array
void display(string[], int);
void addEntry(string[], int&);
int main()
{
string name[MAXSIZE] = {"raj","casey","tom","phil"};
int numEntries = 4; // number of elements in the array
string choice; // the user choice to add an element or display or exit
cout<<numEntries<<" names were read in."<<endl;
do
{
cout<<endl<<"Enter menu choice (display, add, quit): ";
getline(cin,choice);
if (choice == "display")
{
display(name, numEntries);
cout<<endl;
}
else if (choice == "add")
{
addEntry(name, numEntries);
cout<<endl;
}
else
{
cout<<"bye"<<endl;
}
} while (choice!="quit");
system ("pause");
return 0;
}
void display(string name[], int numEntries)
{
for (int i = 0; i < numEntries; i++)
{
cout<<name[i]<<endl;
}
return;
}
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE-1)
{
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}

getline(cin,name[numEntries]);
numEntries is the number of valid entries in your array. name[numEntries] is the element that is following the last valid entry. Use name[numEntries-1].
Or even better, use std::vector instead of C arrays, after all, you are writing in C++.

Your program works, you are just pointing the the wrong location in your array in addEntry. Remember that arrays in C++ are 0-based, try incrementing the value of numEntries AFTER inserting the element in your array, for example:
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE)
{
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries++]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}

The bug in your code is in the following lines:
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
You need to increment numEntries after the call to getline. Use:
cout<<"Enter name of the person to add: ";
if ( getline(cin,name[numEntries]) )
{
// Increment only if getline was successful.
numEntries++;
}

Related

Why won't the string push or pop in stack [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
This is an assignment given to me.
I am a noob just started programming.
The string as a whole won't push onto the stack and how to pop it.
Problem statement:- divide a whole string consisting of a full name, divide the string into 3 parts to get the first name middle name and surname and display them in the order of surname first name middle name USING STACKS ONLY.
I've tried using 2D stack
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string>
using namespace std;
using std :: string;
char s1[100];
char s2[50],s3[50],s4[50];
int i=0,j=0,k=0,max1=9,top=-1;
char stack[10][10];
char re[10];
void push(char val[])
{
if(top>=max1)
{
cout<<"Stack overflow";
}
else
{
top++;
int a=0;
for (int i=0;i<stack[top]['\0'];i++)
{
stack[top][a]=val[i];
a++;
}
}
}
char* pop()
{
if(top<0)
{
cout<<"Stack underflow";
}
else
{
//for(int j=0;j<=top)
for(int i=0;i<stack[top]['\0'];i++)
{
re[i]=stack[top][i];
top--;
return re;
}
}
}
void divstring()
{
for(i=0;s1[i]!=' ';i++)
{
s2[i]=s1[i];
}
s2[i]='\0';
i++;
while(s1[i]!=' ')
{
s3[j]=s1[i];
j++;
i++;
}
s3[j]='\0';
i++;
while(s1[i]!='\0')
{
s4[k]=s1[i];
k++;
i++;
}
s4[k]='\0';
i++;
}
int main()
{
//clrscr();
cout<<"Enter the string: ";
gets(s1);
divstring();
cout<<"The 1 part is "<<s2<<endl;
cout<<"The 2 part is "<<s3<<endl;
cout<<"The 3 part is "<<s4<<endl;
// getch();
push(s1);
push(s2);
push(s3);
cout<<pop();
return 1;
}
There are no compile time errors but the strings don't get pushed onto the stack nor popped.
There's multiple problems here.
There is no such thing as a 2D stack. A stack is one dimensional. It's got one usable end. In C++, you use std::stack, push(), pop() and empty().
You need to get rid of the global variables.
You seem to want to implement your own stack. You need to decide, do you want to implement a stack, that is one question. Or, do you want to use an existing stack to perform the assignment? that's a different question. I can't tell between the two.
You should use std::string.
You don't handle boundary condition. For example passing a string without spaces will loop infinitely in
for(i=0;s1[i]!=' ';i++)
The push function is very confused, here's a working version
void push(char val[])
{
if (top >= max1)
{
cout << "Stack overflow";
}
else
{
top++;
int i = 0;
for (; val[i] != '\0'; i++)
stack[top][i] = val[i];
stack[top][i] = '\0';
}
}
There are many ways you could improve this, you could use the C strcpy function instead of copying your strings by hand. Or, heaven forbid, you could use some C++, like std::string and std::stack.

C++ code compiles but doesn't run [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 6 years ago.
Improve this question
I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
Here is the full code in case I am wrong of the source of the problem:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
Be consistent in what you do. Including <stdlib.h> and <ctime> looks strange. Either include <cstdlib> and <ctime>, or include <stdlib.h> and <time.h>.
using namespace std;
Don't do this. This using imports all names from the std namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write std::time instead of the unqualified time. This makes it perfectly clear that you are referring to the time from the standard library instead of one that you might have defined yourself.
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
The cards should not be represented as strings, but as a separate data type called Card, with properties like suit and rank and a to_string method.
public:
void set_name(string a){name=a;}
To make your program fast, pass a as const std::string & instead of a simple string. This will prevent some copying of data. You should give a better name to the parameter, e.g. void set_name(const std::string &name) { this.name = name; }.
string print_name(){return name;}
This method does not print anything, therefore it must not be called print_name.
void card_generator();
Methods usually are named with verbs, not with nouns. So generate_cards would be a better name. But what does generate mean here? (I'm not a native English speaker, but would draw_cards describe it accurately?)
string set_cards(int c){return cards[c];}
A method called set_* usually modifies something. This one doesn't. Why did you name it this way?
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
Give better names to the parameters. From reading only this declaration, I have no idea what i and max_i might mean.
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a class Table. This allows you to have multiple independent tables, which is nice for a big tournament.
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
Before reading the choice1 variable, you must initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
Same here. The user hasn't yet entered anything, so how can you check it?
cin>>i;
Add error handling for every input by enclosing it in an if clause: if (std::cin >> i) {.
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
Don't use arrays, use a std::vector instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single 6 in your program.
player[0].card_generator();
max_i = i;//max_i is nb of players
Why do you call this variable max_i, when the comment says that max_players would be a better name?
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
What does the V in tempV mean?
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be % 52.
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
Captain Giraffe has answered this question in the comments. If any newbies like me face a similar problem look up what a debugger is, as errors like these are called run-time errors. Check this page for a simple explanation: http://www.cplusplus.com/forum/articles/28767/ .

trouble with friend function [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 6 years ago.
Improve this question
so my program is that i want the user to enter information about a board so everything is working except the part where i need the user to enter the value of attitude then add another number to increase that attitude so I'm stuck at this. As you can see I declared this function as a friend but when I enter the number that I need to increase it to the value of attitude) it stays the same! I hope I made clear the problem I'm facing! and I'd appreciate some help
#ifndef BOARD_H
#define BOARD_H
class Board {
friend void incAttitude(Board &);
public:
friend void incAttitude(Board &);
static int boardcount;
Board(int=5,int=3,double=1.5,char* ='\0');
~Board();
Board &setBoard(int,int,double,char*);
char getLocation();
Board &print();
double surface();
private:
const int length;
int width;
double attitude;
char location[30];
};
#endif
#include<iostream>
#include<cstring>
#include<string>
#include<assert.h>
using namespace std;
#include "Board.h"
int Board::boardcount=0;
Board::Board(int l,int w,double a,char* lo)
: length(l)
{
width=w;
attitude=a;
location[0]='\0';
boardcount++;
}
Board::~Board(){
boardcount--;
}
Board &Board::setBoard(int l,int w,double a,char* lo)
{
width=(w>=2 && w<=5)?w:3;
attitude=(a>=1.5 && a<=2.8)?a:1.5;
strncpy_s(location,lo,29);
location[29]='\0';
return *this;
}
char Board::getLocation(){
return *location;
}
double Board::surface(){
return length*width;
}
void incAttitude(Board &h)
{
double incAttitude;
cout<<"enter to increase attitude "<<endl;
cin>>incAttitude;
h.attitude+=incAttitude;
cout<<"the attitude of the board after the increase : "<<h.attitude<<endl;
}
Board &Board::print(){
cout<<"the length of the boarad : "<<length<<endl;
cout<<"the width of the board : "<<width<<endl;
cout<<"the height of the board : "<<attitude<<endl;
cout<<"the location of the board : "<<location<<endl;
cout<<"the surface of the board : "<<surface()<<endl;
return *this;
}
int main(){
Board hh;
Board *boardptr;
int count,len,wid;
double att;
char locat[30];
cout<<"how many boards do you need to create ? "<<endl;
cin>>count;
boardptr = new Board[count];
assert(boardptr!=0);
for (int i=0; i<count; i++){
cout << "Enter the length: ";
cin >>len;
cout << "Enter the width: ";
cin >> wid;
cout << "Enter the attitude: ";
cin >> att;
incAttitude(hh);
cout<<"Enter the location: ";
cin >>locat;
boardptr[i].setBoard(len,wid,att,locat);
cout<<"------------------------------------------"<<endl;
if (strcmp("NewYork",locat) == 0)
{
boardptr[i].setBoard(len,wid,att,locat).print();
}
}
delete [] boardptr;
system("pause");
return 0;
}
You have an array of Boards, which is called boardptr. But then what is hh? A single board. What does it do? Nothing! But you are using it in incAttitude(hh);! It does increase the altitude, but not on the board boardptr[i] (that you are using), rather on hh.
Secondly, you are never setting att, which means the altitude is always 1.5 (that's the default value). So incAttitude adds the number to 1.5. You could pass att to incAttitude for example.
Then if your comparison condition, why do you set the board again? It resets every value the user chose. You don't need to, because you already call setBoard a few lines early. The data you set with setBoard is saved in that array, so you don't need to override the data with the exact same data. Just use boardptr[i].print().
char arrays, strcmp, raw pointers and fixed size arrays are from C, you should consider the alternatives:
Char arrays -> std::string
strcmp -> if (str == "foo")
Raw pointers -> Smart pointers (or in your case (because they are used as arrays) std::array or std::vector - std::vector for dynamic size arrays)
Fixed size arrays -> std::array

how to use gets function in c++ code?

In the main function of this code in the case 2 of switch case after entering the string program terminates! What is the problem with the code?
/*this code is a implementation of bubble sort algorithm*/
#include <iostream>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<dos.h>
using namespace std;
int counter;
template <class T>//template created
class program//class which holds all the sorting functions
{
public:
T *v,x;
int j,k,l,siz,flag;
time_t t1,t2;
char c;
public:
void sortlist()//fn to sort characters and numbers
{
cout<<endl<<"------->>INTERMEDIATE STEPS<<-------";
for(k=1;k<=siz-1;k++)//sorting using a bubble sort
{ flag=0;
cout<<endl<<"PASS : "<<k<<endl;
j=0;
while(j<=siz-1-k)
{
if(v[j]>v[j+1])//comparing two consecutive elements
{
x=v[j+1];
v[j+1]=v[j];
v[j]=x;
flag++;
}
for(l=0;l<siz;l++)
{
cout<<v[l]<<" ";
}
cout<<endl;
j++;
}
cout<<"COMPARISONS:"<<(siz-k)<<endl;
if(flag==0)
{
cout<<endl<<"----->NO need to carry out more passes"<<endl<<"List is already sorted"<<endl;
break;
}
}
}
void stringsort()//fn to sort the strings
{
T a[90][20],b[1][20];
cout<<"enter the size of list:";
cin>>siz;
cout<<"enter the list:";
cin.ignore();
for(j=0;j<siz;j++)
{
gets(a[j]);
}
cout<<endl<<"------->>INTERMEDIATE STEPS<<-------";
for(k=1;k<=siz-1;k++)//sorting using bubble sort
{
flag=0;
cout<<endl<<"PASS : "<<k<<endl;
j=0;
while(j<siz-k)
{
x=strcmp(a[j],a[j+1]);//comparing two consecutive string
if(x>0)
{
strcpy(b[1],a[j+1]);
strcpy(a[j+1],a[j]);
strcpy(a[j],b[1]);
flag++;
}
for(l=0;l<siz;l++)
{
cout<<a[l]<<" ";
}
cout<<endl;
j++;
}
cout<<endl<<"COMPARISON:"<<(siz-k)<<endl;
if(flag==0)
{
cout<<endl<<"No need to carry out more passes"<<endl<<"List is already Sorted"<<endl;
break;
}
}
cout<<"SORTED LIST:"<<endl;
for(j=0;j<siz;j++)
{
cout<<endl<<a[j]<<endl;
}
}
};
int main()//main fn
{
int x;
char c;
do
{
program <char> p1;
program <int> p2;
cout<<endl<<"To sort a list of NUMBERS enter -> 1"<<endl<<endl<<"To sort string of CHARACTERS enter -> 2"<<endl<<endl<<"To sort a list OF STRINGS and DOUBLE_STRINGS enter -> 3";
cout<<endl<<endl<<"Enter either 1 OR 2 OR 3:";
cin>>x;
switch(x)
{
case 1://to sort list of numbers
{
cout<<endl<<"enter the size of list: ";
cin>>p2.siz;
cout<<"enter the list: "<<endl;
p2.v=new int[p2.siz];
for(p2.l=0;p2.l<=p2.siz-1;p2.l++)
{
cin>>p2.v[p2.l];
}
p2.sortlist();//sort and search in numbers
cout<<endl<<"SORTED LIST:"<<endl;//sorted list after the bubble sort
for(x=0;x<=(p2.siz)-1;x++)
{
cout<<p2.v[x]<<endl;
}
}
break;
case 2://to sort string of character
{
cout<<"enter the string of characters:";
cin.ignore()
gets(p1.v);
p1.siz=strlen(p1.v);
p1.sortlist();//sort in characters
cout<<endl<<"SORTED STRING:"<<p1.v;
}
break;
case 3://to sort list of strings
{
p1.stringsort();//sort list of string
}
break;
default:
cout<<"INVALID_CHOICE"<<endl<<endl;
}
cout<<endl<<"do u want to enter another list?y/n";
cin>>c;
}
while(c=='y');
return 0;
}
gets requires that you pass a pointer to enough storage space to hold the string that gets read. Your program passes an uninitialized pointer.
You're not really allowed to do anything with uninitialized values, so in theory your program can crash before it even enters the gets function.
Since the user can pass any amount of data to gets and your program would be responsible for storing it, the function is deprecated. It doesn't even exist any more in the C++ standard library as std::gets since 2011, although ::gets will probably always be available in POSIX. The short answer is, "don't."
You might consider std::string and std::getline instead.

C++ run error: pointer being freed was not allocated [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm learning c++ and am working on a program that keeps giving me a 'pointer being freed was not allocated' error. It's a grocery store program that inputs data from a txt file, then user can enter item# & qty. I've read through similar questions but what's throwing me off is the 'pointer' issue. I would appreciate if someone could take a look and help me out. I'm using Netbeans IDE 7.2 on a Mac.
I'll just post the whole piece I have so far. Thx.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Product
{
public:
// PLU Code
int getiPluCode()
{
return iPluCode;
}
void setiPluCode( int iTempPluCode)
{
iPluCode = iTempPluCode;
}
// Description
string getsDescription()
{
return sDescription;
}
void setsDescription( string sTempDescription)
{
sDescription = sTempDescription;
}
// Price
double getdPrice()
{
return dPrice;
}
void setdPrice( double dTempPrice)
{
dPrice = dTempPrice;
}
// Type..weight or unit
int getiType()
{
return iType;
}
void setiType( int iTempType)
{
iType = iTempType;
}
// Inventory quantity
double getdInventory()
{
return dInventory;
}
void setdInventory( double dTempInventory)
{
dInventory = dTempInventory;
}
private:
int iPluCode;
string sDescription;
double dPrice;
int iType;
double dInventory;
};
int main ()
{
Product paInventory[21]; // Create inventory array
Product paPurchase[21]; // Create customer purchase array
// Constructor to open inventory input file
ifstream InputInventory ("inventory.txt", ios::in);
//If ifstream could not open the file
if (!InputInventory)
{
cerr << "File could not be opened" << endl;
exit (1);
}//end if
int x = 0;
while (!InputInventory.eof () )
{
int iTempPluCode;
string sTempDescription;
double dTempPrice;
int iTempType;
double dTempInventory;
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
paInventory[x].setiPluCode(iTempPluCode);
paInventory[x].setsDescription(sTempDescription);
paInventory[x].setdPrice(dTempPrice);
paInventory[x].setiType(iTempType);
paInventory[x].setdInventory(dTempInventory);
x++;
}
bool bQuit = false;
//CREATE MY TOTAL VARIABLE HERE!
int iUserItemCount = 0;
do
{
int iUserPLUCode;
double dUserAmount;
double dAmountAvailable;
int iProductIndex = -1;
//CREATE MY SUBTOTAL VARIABLE HERE!
while(iProductIndex == -1)
{
cout<<"Please enter the PLU Code of the product."<< endl;
cin>>iUserPLUCode;
for(int i = 0; i < 21; i++)
{
if(iUserPLUCode == paInventory[i].getiPluCode())
{
dAmountAvailable = paInventory[i].getdInventory();
iProductIndex = i;
}
}
//PLU code entry validation
if(iProductIndex == -1)
{
cout << "You have entered an invalid PLU Code.";
}
}
cout<<"Enter the quantity to buy.\n"<< "There are "<< dAmountAvailable << "available.\n";
cin>> dUserAmount;
while(dUserAmount > dAmountAvailable)
{
cout<<"That's too many, please try again";
cin>>dUserAmount;
}
paPurchase[iUserItemCount].setiPluCode(iUserPLUCode);// Array of objects function calls
paPurchase[iUserItemCount].setdInventory(dUserAmount);
paPurchase[iUserItemCount].setdPrice(paInventory[iProductIndex].getdPrice());
paInventory[iProductIndex].setdInventory( paInventory[iProductIndex].getdInventory() - dUserAmount );
iUserItemCount++;
cout <<"Are you done purchasing items? Enter 1 for yes and 0 for no.\n";
cin >> bQuit;
//NOTE: Put Amount * quantity for subtotal
//NOTE: Put code to update subtotal (total += subtotal)
// NOTE: Need to create the output txt file!
}while(!bQuit);
return 0;
}
iUserItemCount is never initialised. You're invoking undefined behaviour when you use it as an index.
Because you work with statically allocated arrays you probably stumbled upon writing after the end of the array.
You state that the file has exactly 21 entries but what happens with the eof condition? If you read the last entry, the stream still doesn't have the eof bit set. This only happens when you try to read and there is nothing.
After the 21st entry, the loop still continues because the eof bit is not set. It reads garbage information and tries to store it into paInventory[21], but the array was only 21 in size.
//after last read x=21 and eof not set
while (!InputInventory.eof () )
{
//first read causes eof to be set
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
//Accessing paInventory[21] here which causes your error
paInventory[x].setiPluCode(iTempPluCode);
//...//
}