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.
My boolean function check_gift is not working properly.
I copied a txt file into the vector giftstore. Now I want to check if a given item is in the store. To test the function check_gift I took an item from the actual txt file but the function gives the wrong answer. It returns false instead of true.
What am I doing wrong?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;
typedef vector<string> Wishes;
int size(Wishes& w){ return static_cast<int>(w.size()); }
struct Wishlist
{
double budget;
Wishes wishes;
};
struct Gift
{
double price;
string name;
};
typedef vector<Gift> Giftstore;
int size(Giftstore& g) { return static_cast<int>(g.size()); }
void read_wishlist_into_struct(ifstream& infile, Wishlist& wishlist)
{
double b;
infile>>b;
wishlist.budget=b;
int i=0;
string name;
getline(infile,name);
while(infile)
{
wishlist.wishes.push_back(name);
i++;
getline(infile,name);
}
infile.close();
}
void show_wishlist(Wishlist wishlist)
{
cout<<"Budget: "<<wishlist.budget<<endl<<endl;
cout<<"Wishes: "<<endl;
for(int i=0; i<size(wishlist.wishes); i++)
{
cout<<wishlist.wishes[i]<<endl;
}
cout<<endl;
}
void read_giftstore_into_vector(ifstream& infile, Gift& gift, Giftstore& giftstore)
{
double p;
string name;
int i=0;
infile>>p;
while(infile)
{
gift.price=p;
getline(infile,name);
gift.name=name;
giftstore.push_back(gift);
i++;
infile>>p;
}
infile.close();
}
void show_giftstore(Giftstore giftstore)
{
cout<<"All possible gifts in giftstore: "<<endl<<endl;
for(int i=0; i<giftstore.size(); i++)
{
cout<<giftstore[i].price<<"\t"<<giftstore[i].name<<endl;
}
cout<<endl;
}
bool check_gift(Giftstore giftstore, string giftname)
{
int i=0;
while(i<size(giftstore))
{
if(giftstore[i].name==giftname)
{
cout<<"Yes"<<endl;
return true;
}
else
{
i++;
}
}
return false;
}
void clear(Wishlist& b)
{
b.budget=0;
while(!b.wishes.empty())
{
b.wishes.pop_back();
}
}
void copy(Wishlist a, Wishlist& b)
{
b.budget=a.budget;
for (int i=0; i<size(b.wishes); i++)
{
b.wishes.push_back(a.wishes[i]);
}
}
int main ()
{
ifstream infile2("giftstore.txt");
Gift gift;
Giftstore giftstore;
read_giftstore_into_vector(infile2, gift, giftstore);
show_giftstore(giftstore);
string giftname;
giftname="dvd Up van Pixar";
bool x;
x=check_gift(giftstore, giftname);
cout<<"in store?: "<<x<<endl;
return 0;
}
Learn how to debug. If you cannot trace line-by-line through your code, then try to keep some kind of log.
For now at least output this to the console.
In your case
1. Verify the input file opened successfully
2. Print out each gift as you read it in.
would be a good way to start.
If you want to be able to put multiple log statements in and then remove them later, you can use a macro which can be turned off in one place.
Logging is a fairly tricky skill to be effective for large projects which continue to run into production, however you should learn how to do it in the short-term to debug your program.
We here cannot even see what is in your input file. This is why people are downvoting your question.
Ok: Now you've told me your issue is you need to trim whitespace from the front of each string you read in.
There are multiple ways to do that but
trimmed = s.substr( s.find_first_not_of(" \n\r\t" ) );
will probably work for now.
However my original answer still holds: please learn to debug. If you'd outputted the strings as you read them in, you would have seen these leading spaces.
Related
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 3 years ago.
Improve this question
\main112.cpp In function 'int main()':
63 36 \main112.cpp [Error] 'counter' was not declared in this scope
28 \Makefile.win recipe for target 'main112.o' failed
#include <string>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
struct Person
{
string name;
string race;
int weight;
void write();
void show();
void check();
};
void Person::show()
{
cout<<"ÔÈÎ: "<<name<<endl;
cout<<"Íîìåð ðåéñà: "<<race<<endl;
cout<<"Âåñ áàãàæà: "<<weight<<endl;
}
void Person::write()
{
cout<<"Ââåäèòå ÔÈÎ: ";
getline(cin,name);
cout<<"Ââåäèòå íîìåð ðåéñà: ";
getline(cin,race);
cout<<"Ââåäèòå âåñ áàãàæà: ";
cin>>weight;
cin.ignore();
}
void Person::check()
{
int counter = 0;
if(weight>10)
{
counter++;
}
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(0, "Russian");
Person* persons=new Person[4];
for (int i = 0; i < 4; i++)
{
persons[i].write();
}
for (int i = 0; i < 4; i++)
{
persons[i].show();
persons[i].check();
}
cout<<"Ñ áàãàæîì áîëüøå 10 êã: "<<counter<<" ÷åëîâåê"<<endl;
delete[] persons;
return 0;
}
Program that works the way its coded and should work, without this problem
Homework:
Write a program for processing passenger information. Information includes:
1) Full name of the passenger.
2) Flight number.
3) Luggage weight
The program should allow the user to:
1) Read data from the keyboard and display it.
2) Calculate the number of passengers with the weight of baggage which is more than 10 kg
The problem here is you're defining counter in the scope of the function Person::check().
Every time you run the check function a new variable called counter is created set to be the value 0. Then once it's through running that function it ceases to exist.
A quick and dirty way of fixing this would be declaring counter as a global variable.
#include <string>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
int counter = 0;
struct Person
{
string name;
string race;
int weight;
void write();
void show();
void check();
};
void Person::show()
{
cout<<"ÔÈÎ: "<<name<<endl;
cout<<"Íîìåð ðåéñà: "<<race<<endl;
cout<<"Âåñ áàãàæà: "<<weight<<endl;
}
void Person::write()
{
cout<<"Ââåäèòå ÔÈÎ: ";
getline(cin,name);
cout<<"Ââåäèòå íîìåð ðåéñà: ";
getline(cin,race);
cout<<"Ââåäèòå âåñ áàãàæà: ";
cin>>weight;
cin.ignore();
}
void Person::check()
{
if(weight>10)
{
counter++;
}
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(0, "Russian");
Person* persons=new Person[4];
for (int i = 0; i < 4; i++)
{
persons[i].write();
}
for (int i = 0; i < 4; i++)
{
persons[i].show();
persons[i].check();
}
cout<<"Ñ áàãàæîì áîëüøå 10 êã: "<<counter<<" ÷åëîâåê"<<endl;
delete[] persons;
return 0;
}
A better way would be defining counter as a member variable of your struct then you can get the value of each of the person objects' counter variable at anytime after declaring the object.
Familiarize yourself with the concept of scope.
Because its scope is the function Person::check, counter is only visible within the bounds of Person::check. No other parts of the program are allowed to interact with it.
Suggested solution:
Change Person::check (and its declaration) to return a boolean. Example:
bool Person::check() const
{
return weight>10;
}
The method is declared const to promise that this function will not change the object. This is done to prevent errors and allow a function that should not change the object to be used on a constant Person. This can prevent subtle errors from creeping into the code.
Now a user can check a Persons baggage weight and do with the result of check whatever they want. In the case of main, it wants to keep a count. There is no reason for anyone but main to know what it does, so counter should be scoped by main. eg:
int main()
{
...
int counter = 0;
for (int i = 0; i < 4; i++)
{
persons[i].show();
if (persons[i].check())
{
counter++;
}
}
cout<<"Ñ áàãàæîì áîëüøå 10 êã: "<<counter<<" ÷åëîâåê"<<endl;
...
}
Side note: There doesn't seem to be a need for persons to be dynamically allocated. Consider replacing
Person* persons=new Person[4];
with
Person persons[4];
and removing
delete[] persons;
If you are dynamically allocating in preparation for a variable number of Persons, prefer to use std::vector
std::vector<Person> persons;
and push_back or emplace_back Persons as they are introduced.
Here's how you fix it. Declare counter in main, make check return bool, and count the number of times it returns false. This encapsulates counter and it makes more sense for check to actually return a Boolean value. Here's what the body of for loop should do:
if (!persons[i].check())
++counter
The error message is correct, because there is no counter in main. You only declare counter here:
void Person::check()
{
int counter = 0;
if(weight>10)
{
counter++;
}
}
and its scope is limited to that method. Actually each time the function is called you get a new counter which gets initialized to 0.
If instead you make counter a member you can keep its value across multiple calls to the method:
class Person() {
public:
int counter = 0;
int check() {
if (weight > 10) ++counter;
}
// ...other stuff left out
};
I also changed the method to return the value of the counter (otherwise you would have to write a getter or some means to get its value).
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/ .
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 9 years ago.
I'm stucked at 1 exercise which was at the end of the chapter 2 ! My problem with this exercise is that I can't figure out how to make logically loop to ask several times the input ! I wrote the code which ask twice for the input ! Previously with book provided header I did that task easy but that way didn't work anymore . So I'll give you the exercise and code and hope you can help me. And sorry for my English.
Exercise
Write program which will have a class in same place where you main function.
Write Code which will read several transaction with same Book Number and count each transaction with that book number.
My Code
#include <iostream>
#include <string>
using namespace std;
//Data structure Code
struct Sales_Data
{
std::string bookNo;
unsigned unit_sold;
double revenue;
};
int main()
{
Sales_Data data1,data2; //Data wich will hold input
double price; //Price per book used to calculate total revenue
// Checking if there was data input of book number units sold and price
if (std::cin>>data1.bookNo>>data1.unit_sold>>price)
{
int cnt=1; //Start Counter
data1.revenue=data1.unit_sold*price;// data1 calculating total revenue from price and unit_sold
while (std::cin>>data2.bookNo>>data2.unit_sold>>price)
{
data2.revenue=data2.revenue*price;
//checking if book name is same
if (data1.bookNo == data2.bookNo)
{
++cnt; //Incrementing counter if they same
unsigned totalCnt=data1.unit_sold+data2.unit_sold;
double totalRevenue=data1.revenue+data2.revenue;
//Print out result
std::cout<<cnt<<data1.bookNo<<" "<<totalCnt<<" "<<totalRevenue<<" ";
getchar();
getchar();
getchar();
if (totalCnt != 0)
std::cout<<totalCnt/totalRevenue;
else
std::cout<<"(No Sales)"<<std::endl;
return 0;
}else{
std::cerr<<"Book numbers isn't same"<<std::endl;
return -1;
}
}
}
return 0;
}
And also wast sure why but the revenue gives me garbage number.
Thank you for your time.
Did you init the data2.revenue before using it?
data2.revenue=data2.revenue*price;
To init data2, you could:
struct Sales_Data
{
std::string bookNo;
unsigned unit_sold;
double revenue;
Sales_Data(std::string s = "", unsigned u = 0, double r = 0)
: bookNo(s), unit_sold(u), revenue(r) {}
};
or
Sales_Data data2 = { "a", 0, 0 };
or
Sales_Data data2;
data2.bookNo = "";
data2.unit_sold = 0;
data2.revenue = 0;
For multiple inputs:
#include <map>
#include <string>
#include <iostream>
using namespace std
int main()
{
map<string, Sales_Data> count;
Sales_Data data;
while (cin >> data.bookNo >> data.unit_sold) { // <- this will allow you read multiple transactions
if (map.find(data.bookNo) != count.end()) {
count[data.bookNo].unit_sold += data.unit_sold;
// and do some other thing.
} else {
count[data.bookNo] = data.
}
}
return 0;
}
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.
Ok.. So I'm working on this code on C++. Code is below..
#include <iostream>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
vector<int> makePerson(int n)
{
vector<int>person;
for(int i=0;i<3;i++)
{
person.push_back(rand()%255+1);
}
return person;
}
vector<vector<int> > makeGeneration(int n)
{
vector<vector<int> > generation;
for(int i=0;i<n;i++)
{
generation.push_back(makePerson(i));
}
return generation;
}
vector<int> createChild(vector<vector<int> > &parentGeneration, double mutationRate)
{
int maleParent = (rand()%parentGeneration.size())+1;
int femaleParent = (rand()%parentGeneration.size())+1;
bool checkGender = true;
while(checkGender)
{
if(maleParent==femaleParent)
{
checkGender = true;
}
else
{
checkGender = false;
break;
}
}
vector<int> child;
vector<int> temp;
for(int i=0;i<3;i++)
{
temp.push_back(parentGeneration.at(maleParent).at(i));
temp.push_back(parentGeneration.at(femaleParent).at(i));
}
for(int i=0;i<3;i++)
{
child.push_back(temp.at((rand()%3)+1));
}
temp.clear();
for(int i=0;i<3;i++)
{
if((mutationRate*100) > (rand()%100)+1)
{
child.at(i)=(rand()%255)+1;
}
}
return child;
}
int main()
{
int N,k,g;
N=1000;
k=2;
double m=0.05;
double d=0.05;
srand(static_cast<unsigned int>(time(0)));
vector<vector<int> > parentGeneration;
vector<vector<int> > childGeneration;
parentGeneration = makeGeneration(N);
for(int i=0;i<parentGeneration.size();i++)
{
for(int j=0;j<3;j++)
{
cout<<parentGeneration.at(i).at(j)<<endl;
}
cout<<endl;
}
cout<<"reach"<<endl;
for(int i=0;i<(1000);i++)
{
childGeneration.push_back(createChild(parentGeneration,m));
}
cout<<"***CHILD GENERATION***"<<endl;
for(int i=0;i<childGeneration.size();i++)
{
for(int j=0;j<3;j++)
{
cout<<childGeneration.at(i).at(j)<<endl;
}
cout<<"i="<<i<<endl;
cout<<endl;
}
return 0;
}
So, the errors are:
Microsoft C++ exception: std::out_of_range at memory location 0x002cf6c4.
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer dec
I think it's some problem with the vector and the random generator because this error is random. It sometimes works till 1000 and sometimes stops in between.
Any suggestions.
Really urgent..
PLEASEEEE
Thanks in advane :D
I faced similar issues with the code. I finally settled on using Microsoft's Application Verifier which allowed me to zero in on the issue. Find Application Verifier and download it. Then run the executable appverifier.exe which is in C:\Windows\System32 folder. Select your executable and enable the memory checking. Then run your code in visual studio as you always do and it should jump at or near where the issue is. It won't do all your work for you, but if you know your code it'll surely help.
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);
//...//
}