C++ code compiles but doesn't run [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 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/ .

Related

access to array elements from different function but same class

I have class that contains some functions with an array. One of them called pick, this function does not has an array but i want to display array element from other function, once i write code to display array element i can not get the element, although the code work and if i add normal text it will display but can not display array elements, i will attach the code below:
Note i did not attache full code only important parts
#include <iostream>
#include<stdlib.h>
#include <string>
using namespace std;
// global variable
string plantType;
int temperatures ;
string water;
string sunExposure;
bool pet;
string plant1,plant2,plant3;
class inside{
public:
void low(){
string plant1 [3]={"Snake plant","Spider plant","Aloe Vera plant"};
for(int i =0; i<3; i++){
cout << "* "<< plant1[i]<<endl;
}
}
void medium(){
string plant2 [5]={"Pothos plant","Dracaena plant","ZZ plant","Rubber plant","Philodendron Green plant"};
for(int i =0; i<5; i++){
cout << "* "<< plant2[i]<<endl;
}
}
void high(){
string plant3 [2]={"Bird’s Nest Fern plant","Peace Lily plant"};
for(int i =0; i<2; i++){
cout << "* "<< plant3[i]<<endl;
}
}
void pick(){
cout <<"Best choice for you is: ";
if (temperatures >= 13 && temperatures <=29 ){
if(water=="low"){
if(sunExposure=="fully"){
cout<<"test"<<endl;
if(pet==true){
cout<<plant1[1]<<endl; //this line cannot be executed
}
}
}}}
int main(){
cout <<"Where do you want to grow the plant (inside), or (outside)"<<endl;
cin>>grow;
if (grow == "inside"){
//inside home
cout<<endl<<"inside"<<endl;
cout<<"Enter the Temperature in (Celsius scale 13-29)"<<endl;
cin>>temperatures;
cout<<"Enter water level (low - medium - high)"<<endl;
cin>>water;
cout<<"Enter Sun Exposure (fully - partly - shady)"<<endl;
cin>>sunExposure;
cout<<"Do you have pet (true or false)? "<<endl;
cin>>pet;
inside inside;
inside.pick();
}
}
The string variables plant1[3], plant2[3] & plant3[3] are only visible to low(), medium(), high() but they're not for each other. For example, you're something trying to access a locally declared variable of foo() function in bar() function, which is impossible.
Secondly, you're trying to access plant1[3] data member in pick() but compiler doesn't know where you've actually defined those three plants' name outside of that function, just it knows plant1 variable with no arrays which is declared in the private section of the class. Hence, there's a good chance your code will get fail.
Rather you could just declare the same thing in this way:
class inside {
std::string plants1[3] = {"...", ...}; // these variables are
std::string plants2[3] = {"...", ...}; // only visible inside the
std::string plants3[3] = {"...", ...}; // class member functions
.
.
}
And after that, you'll get the line executed successfully.

What is the problem I am having with using arrays with classes?

I have been working on a project for my computer science class and have encountered an issue with the code working. I am shown no error except when I try to compile and I get an error that reads:
Exception thrown: write access violation.
_Left was 0xCCCCCCCC.
The purpose of my project is to take a list of names from an external file, read them into an array, sort said array and then output the sorted list all while using a class for the code.
Here is a copy of my code and I would like to extend my gratitude to whoever can help me through my issue:
**Header File**
#include <iostream>
using namespace std;
class person
{
public:
person();
bool get(ifstream&);
void put(ofstream&);
private:
int capacity = 0;
string first_name[CAPACITY];
string last_name[CAPACITY];
int age[CAPACITY];
};```
**Header function definitions cpp file**
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
const int CAPACITY=20;
using namespace std;
#include "Person.h"
//Names constructor
//Postcondition both first name and last name initialized to zero
person::person()
{
first_name[CAPACITY] = "";
last_name[CAPACITY] = "";
age[CAPACITY]=0;
}
bool person::get(ifstream& in)
{
in >> first_name[CAPACITY] >> last_name[CAPACITY] >> age[CAPACITY];
return(in.good());
}
void person::put(ofstream &out)
{
out << first_name[CAPACITY] << last_name[CAPACITY] << age[CAPACITY];
}
**cpp file which holds main**
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
const int CAPACITY = 20;
using namespace std;
#include "Person.h"
void pop(string *xp, string *yp);
void sort(string name[CAPACITY], int count);
int main()
{
class person names[CAPACITY];
ifstream infile;
ofstream outfile;
string filename;
string name[CAPACITY];
int n = 0;
cout << "Enter the file name you wish to open" << endl;
cin >> filename;
infile.open(filename + ".txt");
outfile.open("Person_New.txt");
if (infile.fail())
{
cout << "The file requested did not open" << endl;
exit(1);
}
while (!infile.eof())
{
names[n].get(infile);
n++;
}
sort(name, CAPACITY);
for (int i = 0; i < CAPACITY; i++)
{
names[i].put(outfile);
}
cout << "The file has been created" << endl;
infile.close();
}
void pop(string *xp, string *yp)
{
string temp = *xp;
*xp = *yp;
*yp = temp;
}
void sort(string name[CAPACITY], int count)
{
int i, j;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - i - 1; j++)
{
if (name[j] > name[j + 1])
{
pop(&name[j], &name[j + 1]);
}
}
}
}
Once again Thank you for any support
It sounds to me like the compiler is getting upset that you are trying to write (i.e. assign a value) at an address that you do not have permission to access. I believe your constructor for the class person might be at fault because of how this class stores its variables, as well as the class header:
Constructor for the class person:
`person::person(){
first_name[CAPACITY] = "";
last_name[CAPACITY] = "";
age[CAPACITY] = 0;
}`
Class header for the class person:
`class person{
public:
//stuff
private:
int capacity = 0;
std::string first_name[CAPACITY];
std::string last_name[CAPACITY];
int age[CAPACITY];
//more stuff
}`
C++ is very specific about its naming conventions, so it makes a distinction between capacity and CAPACITY. Because of this, the variable CAPACITY is not defined within the Person.h file.
Also, because CAPACITY is set to a fixed value in your Person.cpp file, whenever you use first_name[CAPACITY], last_name[CAPACITY], or age[CAPACITY] to assign new values, you are only updating the values at the index equal to CAPACITY unless you update the value of CAPACITY itself. In the code you provided, CAPACITY is equal to 20, so your program attempts to update exclusively index 20 with each method call. This will likely cause issues since the person class only attempts to make its arrays on the runtime stack, with a size of 0 each.
Separately, it seems like you want an array of people, but it appears that you are attempting to use a single person object to store the names and ages of multiple people by making these all arrays. Instead, I would recommend making first_name, last_name, and age not arrays, but rather single variables. Then, you can manipulate an array of type person using your CAPACITY variable. You got pretty close, but you can instead declare it as person myPersonArray[CAPACITY] (no need to mention "class" in front of it -- just be sure that you have #include "Person.h" in your main.cpp file). When you want to update a specific person, you can perform an operation like myPersonArray[updateThisIndexNum].update(newFirstName, newLastName, newAge) or some logical equivalent.
As a final note, I almost always highly recommend against using !infile.eof() to control your while loop when reading any file because eof() only indicates whether you have tried to read past the end of an input file. I would highly recommend checking out this post on Stack Overflow where people far more knowledgeable than I explain exactly why this is usually dangerous and how to avoid it.

Error - int 'counter' was not declared in this scope [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 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).

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

C++ Int getting random value after function that isn't supposed to change it

Okay - yes, this is homework, but it isn't mine. I have a friend taking an introductory C++ course who asked me for help, and I helped them write this program, but there is one weird bug that I can't figure out. Any helpful suggestions would be greatly appreciated. Thanks!!
The following is the code. The problem is that after the add_loop function, the int loop_size gets a random value. Within the function, it has the value it is supposed to have, but afterwards, it changes.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define STRING_SIZE 50
void get_template (char StemLoop [])
{
char Template [STRING_SIZE];
cout<<"Please enter a template for the stem:";
cin>> Template;
strcpy (StemLoop, Template);
}
void add_loop (char StemLoop[], int loop_size)
{
char random_loop [STRING_SIZE];
int random_array[STRING_SIZE];
for (int i=0; i<loop_size; i++)
{
random_array[i] = rand() % 4;
if (random_array[i]==0)
random_loop[i]='A';
else if (random_array[i]==1)
random_loop [i]='U';
else if (random_array[i]==2)
random_loop [i]='G';
else if (random_array[i]==3)
random_loop [i]='C';
}
strcat (StemLoop, random_loop);
}
void add_complement(char StemLoop[], int loop_size)
{
int x =strlen(StemLoop);
int j=0;
char complement [STRING_SIZE]="";
for (int i=0; i<(x-loop_size); i++)
{
if (StemLoop[i]=='A')
complement[j]='U';
else if (StemLoop[i]=='U')
complement[j]='A';
else if (StemLoop[i]=='G')
complement[j]='C';
else if (StemLoop[i]=='C')
complement[j]='G';
j++;
}
strcat(StemLoop,complement);
}
void main()
{
int loop_size=0;
cout<<"Please enter the size of the loop: ";
cin>>loop_size;
char StemLoop [STRING_SIZE];
//Part1: the template
get_template (StemLoop);
//This is supposed to be the function that adds the loop of random "genes".
//It works, and within it the int loop_size is the correct value...
add_loop (StemLoop, loop_size);
/*...but here it is a random number. It's as if the random value generated
within the function is getting assigned to it. And of course, it's throwing off the
entire program.
*/
//Part#3: the complement
add_complement (StemLoop, loop_size);
cout<<"The complete stem-loop strand is:"<<StemLoop<<endl;
}
You're not 0-terminating random_loop before you use it in strcat, so strcat can write all over your stack. Try this:
random_loop[i] = 0;
strcat (StemLoop, random_loop);
A more serious problem could be that you're not checking you have enough room to strcat.