How to debug a C++ program using arrays? - c++

#include<iostream.h>
#include<conio.h>
class XIIB
{
char name[30];
int age;
int roll;
float marks;
public:
void getdata(char a[30],int i,int j,float k)
{
name[30]=a[30];
age=i;
roll=j;
marks=k;
}
void putdata(void)
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Roll:"<<roll<<endl;
cout<<"Marks:"<<marks<<endl;
}
};
const int size=5;
XIIB student[size];
void main()
{
char x[30];
int ag;
int rno;
float mrks;
for(int p=0;p<size;p++)
{
cout<<"Enter Name,Age,Roll and Marks of Student"<<p+1<<endl;
cin>>x>>ag>>rno>>mrks;
student[p].getdata(x,ag,rno,mrks);
}
for(p=0;p<size;p++)
{
cout<<"Student"<<p+1<<endl;
student[p].putdata();
}
getch();
}
This program compiles without any error. Also takes the input for Name, Roll No, Age and Marks as expected but it is unable to display the name of the Students. I seem to have made some error in the getdata or putdata functions.

In void getdata(char a[30],int i,int j,float k): name[30]=a[30]; does not make what you expect and is undefined behavior; (this copies the 31st character of a to the 31st character of name, while both strings are only 30 characters long.)
You have to replace name[30]=a[30]; by strcpy(name,a); and this should work.

your getdata has a problem, character arrays cannot be copied like that, try this
void getdata(char a[30],int i,int j,float k)
{
strcpy(name,a); //change this line
age=i;
roll=j;
marks=k;
}
instead of
name[30]=a[30];

Related

Compiler is throwing error in main that this is not declare before

#include<iostream>
#include<string>
using namespace std;
class customerNode{
public:
int c_id;
int quantity;
string c_name;
string type;
customerNode* next_node;
};
class Queue{
public:
customerNode* front=NULL;
customerNode* rear=NULL;
int getc_id();
string getc_name();
int getquantity();
int setc_id(int c_id);
string setc_name(string c_name);
int setquantity(int quantity);
void display();
void enqueue(int c_id,int quantity,string c_name);
void dequeue();
int nor_queue,exp_queue;
};
int Queue::getc_id(){
int c_id;
cout<<"enter customer id:"<<endl;
cin>>c_id;
return c_id;
}
int Queue::getquantity(){
int quantity;
cout<<"enter quantity customer purchased:"<<endl;
cin>>quantity;
return quantity;
}
string Queue::getc_name(){
string c_name;
cout<<"enter customer name:"<<endl;
cin>>c_name;
return c_name;
}
int Queue::setc_id(int c_id){
return c_id;
}
int Queue::setquantity(int quantity){
return quantity;
}
string Queue::setc_name(string c_name){
return c_name;
}
void Queue:: enqueue(int c_id,int quantity,string c_name){
int exp_queue,nor_queue;
cout<<"enter customer information"<<endl;
customerNode* new_node=new customerNode;
new_node->c_id=c_id;
new_node->c_name=c_name;
new_node->quantity=quantity;
new_node->next_node=NULL;
if(front==NULL){
rear=front;
rear=new_node;
rear->next_node=NULL;
}
else{
while(rear->next_node!=NULL)
rear=rear->next_node;}
rear->next_node=new_node;
rear=new_node;
if(new_node->quantity<=5)
{
new_node->type="express";
exp_queue++;
cout<<"customer entered in express queue"<<endl;
cout<<"total customer in express queue="<<exp_queue<<endl;
}
else{
new_node->type="normal";
nor_queue++;
cout<<"customer entered in normal queue"<<endl;
cout<<"total customer in normal queue="<<nor_queue<<endl;
}
}
void Queue::display(){
customerNode* ptr=front;
cout<<"normal queue customer information"<<endl;
while(ptr!=NULL)
{
if(ptr->type=="normal"){
cout<<"custumer name:"<<setc_name(ptr->c_name)<<endl;
cout<<"custumer id:"<<setc_id(ptr->c_id)<<endl;
cout<<"item puchased by custumer :"<<setquantity(ptr->quantity)<<endl;
nor_queue--;
cout<<"total customer in normal queue:"<<nor_queue<<endl;
}
ptr=ptr->next_node;
}
cout<<"express queue customer information"<<endl;
while(ptr!=NULL)
{
if(ptr->type=="normal"){
cout<<"custumer name:"<<setc_name(ptr->c_name)<<endl;
cout<<"custumer id:"<<setc_id(ptr->c_id)<<endl;
cout<<"item puchased by custumer :"<<setquantity(ptr->quantity)<<endl;
nor_queue--;
cout<<"total customer in normal queue:"<<exp_queue<<endl;
}
}
}
main(){
Queue q;
char i;
do{
q.enqueue(c_id,quantity,c_name );
cout<<"do you want to enter another customer?input y or Y for yes and n or N for no:";
cin>>i;
}
while(i=='y'||i=='Y');
q.display();
return(0);
};`
in mian fuction i m getting error c_id,quantity,c_name is not declare before,when i use int c_id,int quantity,string c_name than it shows expected primary expression befor int and strinng..i dont know which expression is missing or how to resolve the error,
please help me to solve this i hve to submit assing as soon as possible.
A much simpler example with similar error is:
#include <iostream>
struct foo {
int x = 0;
int y = 0;
void assign(int a, int b){
x = a;
y = b;
}
};
int main()
{
foo f;
f.assign(x,y);
}
The error is:
<source>: In function 'int main()':
<source>:14:14: error: 'x' was not declared in this scope
14 | f.assign(x,y);
| ^
<source>:14:16: error: 'y' was not declared in this scope
14 | f.assign(x,y);
| ^
x and y are declared in the scope of the class. Instances of foo have members of that name. To access those members you would write f.x or f.y.
c_id,quantity, and c_name are not declared in your main. I am not eniterly sure what you want to do and it is too much code to adress all its issues. Though, if you want to declare variables of that name in main then you need to do that:
int main(){ // main must return int
Queue q;
char i;
int c_id = 42;
int quantity = 0;
string c_name{"some fancy name"};
q.enqueue(c_id,quantity,c_name );
// ...
}
It is a little surprising that you write code with advanced stuff like pointers, classes and what not, but don't know about scope. Try to search for "scope" and read about it.
There are more issues in your code. For example int Queue::setquantity(int quantity){ return quantity;} does not set anything. Though, as I wrote before, this is just way too much code to adress all of them. I can only advise you to start with less code and only write more when you know the code you have already does compile and passes your tests. And thats not just an advise for a beginner, but anybody is making mistakes and you rather want to fix one problem then many at the same time.

errror: invalid conversion from 'const char*' to 'int'

I am trying to add to a class a person's day, month and year of birth. As of now, i am at trying to include the day of birth, had lots of errors, managed to get rid of most of them but i still have this one left(at first, i included at the same time the day, month and year of birth but i had many erros so i decided to try and fix at least one of them). In the code i also have the birth date as a char and that works fine but i need those values to work with them later.
#include <iostream>
#include <cstring>
using namespace std;
class Persoana
{
private:
char nume[20];
char data_nastere[20];
int zi;
public:
Persoana(char *nume="", char *data_nastere="", int zi="");//this is where i have the error
void setNume(char *nume);
char* getNume();
void setDataNastere(char *data_nastere);
char* getDataNastere();
void setZi(int zi);
int getZi();
void afisare();
};
Persoana::Persoana(char *nume, char *data_nastere, int zi)
{
setNume(nume);
setDataNastere(data_nastere);
setZi(zi);
}
void Persoana::setNume(char *nume)
{
strcpy(this->nume, nume);
}
char* Persoana::getNume()
{
return nume;
}
void Persoana::setDataNastere(char *data_nastere)
{
strcpy(this->data_nastere, data_nastere);
}
char* Persoana::getDataNastere()
{
return data_nastere;
}
void Persoana::setZi(int zi)
{
this->zi=zi;
}
int Persoana::getZi()
{
return zi;
}
void Persoana::afisare()
{
cout<<"Nume: "<<nume<<endl;
cout<<"Data nasterii este: "<<data_nastere<<endl<<endl;
cout<<zi<<endl;
}
int main()
{
Persoana p[] = {Persoana("Calin Dorina", "12 02 2000", 12), Persoana("Mihaela Banu", "25 04 2001", 25)};
p[0].afisare();
//p[1].afisare();
}
You try to assign a pointer to literal string (it's pointer to const char which is fist letter in this string) to the integer property z in constructor: int zi="". C++ hasn't default conversion from const char* to int. You should use integer default values for integer properties.
One of you said to declare int zi=0 and thats the right answer. I tried doing it before but where i declared the private variables. Thanks for helping!
In case someone else has this problem, here it is how its supposed to be:
Persoana(char *nume="", char *data_nastere="", int zi=0);

Array Initialization problems: Unexpected behavior

The following program builds perfectly. However, during execution, no matter what value of degree I provide, the program takes only 2 array elements as input. I suppose there might be a problem with the redeclaration of the arrays f[] and fDash[]. In JAVA, arrays can be easily redeclared using the new keyword. Is that possible in c++ too? If not, what is the alternative?
P.S. I am using CodeBlocks 13.12 and compiler settings are standard.
#include <iostream>
#include <cmath>
using namespace std;
class Polynomial
{
public:
void input(void);
void expression(void);
void derivative(void);
double value(double var);
double der(double var);
private:
int f[];
int fDash[];
int degree;
};
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
f[degree+1];
fDash[degree];
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>f[i];
}
for(int i=0;i<degree;i++)
{
fDash[i]=f[i+1]*(i+1);
}
}
void Polynomial::expression()
{
cout<<f[0];
for(int i=1;i<=degree;i++)
{
cout<<" + "<<f[i]<<"*x^"<<i;
}
}
void Polynomial::derivative()
{
cout<<fDash[0];
for(int i=1;i<degree;i++)
{
cout<<" + "<<fDash[i]<<"*x^"<<i;
}
}
double Polynomial::value(double var)
{
double val=0.0;
for(int i=0;i<=degree;i++)
{
val+=f[i]*pow(var,i);
}
return val;
}
double Polynomial::der(double var)
{
double val=0.0;
for(int i=0;i<degree;i++)
{
val+=fDash[i]*pow(var,i);
}
return val;
}
int main()
{
double lb,ub,step,var,accum=0.0,rms;
int counter=0;
Polynomial p;
p.input();
cout<<"\n\n\nPolynomial is:\nf(x) = ";
p.expression();
cout<<"\n\n\nDerivative is:\nf'(x) = ";
p.derivative();
cout<<"\n\n\nEnter x0,x1,Step:\t";
cin>>lb;
cin>>ub;
cin>>step;
cout<<"\n\n\n====================================";
cout<<"\n\nx\t|\tf\t|\tf'\n\n\n";
var=lb;
while(var<=ub)
{
cout<<var<<"\t|\t"<<p.value(var)<<"\t|\t"<<p.der(var)<<"\n";
accum+=pow(p.value(var),2.0);
var+=step;
counter++;
}
cout<<"\n====================================";
accum/=counter;
rms=sqrt(accum);
cout<<"\nRMS energy of f(x) = "<<rms;
return 0;
}
This does not compile on clang, it fails with "error: field has incomplete type 'int []' int f[];" and likewise for fDash.
Let's see how you declared these fields:
int f[];
int fDash[];
In C++, you can declare arrays with statically defined sizes like so:
int f[5];
int fDash[6];
If you want dynamic arrays, which you need in this case, you'd have to declare
int* f;
int* fDash;
and allocate memory for them with
f = new int[5];
You also must release that memory somewhere like so
delete [] f;
But beware - managing your own memory like this is error prone and should be avoided. You should just use std::vector instead, which is the equivalent of java.util.ArrayList:
std::vector<int> f;
std::vector<int> fDash;
And modify your input function like so:
void Polynomial::input()
{
cout<<"Enter degree of polynomial:\t";
cin>>degree;
int input;
for(int i=0;i<=degree;i++)
{
cout<<"Enter coefficient of x^"<<i<<":\t";
cin>>input;
f.push_back(input);
}
for(int i=0;i<degree;i++)
{
fDash.push_back(f[i+1]*(i+1));
}
}
You don't use arrays correctly. You need to allocate memory if you want to use array of variable length. How use arrays in c++ see this and this, or use std::vector

Heapsort using Priority queue C++

My code works for putting data into the array but when I print it out, it always crashes after first number. There must be something wrong with my bubbledown function, could you point out what is wrong with it? Thank you in advance.
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
void bubbleup(int pq[], int back);
void bubbledown(int pq[], int front, int back);
void swap(int &a, int &b);
int main(){
ifstream infile;
ofstream outfile;
string input, output;
int size,number;
int front=1, back=0;
int *pq=new int[size]; // dynamically allocate array
cout<<"What's the input file name?"<<endl;
getline(cin, input); // get the input name
infile.open(input.c_str());// open the input file
while(!(infile.eof())){
infile>>number; // infile to an integer type variable first instead of an array. this is why your program doesn't work!!!!!
back++;
pq[back]=number;
bubbleup(pq,back);
for(int i=1;i<=back;i++)
cout<<pq[i]<<" ";
cout<<endl;
}
cout<<"what's the output file name?"<<endl;
getline(cin, output);
outfile.open(output.c_str());
while(back!=0){
cout<< pq[front]<<endl;
outfile<< pq[front]<<endl;
pq[front]=pq[back];
back--;
bubbledown(pq,front,back);
}
}
//bubbleup function
void bubbleup(int pq[], int back)
{
int fatherindex=back/2;
while(!(pq[back]>=pq[fatherindex])||!(back==1)){
if(pq[back]<pq[fatherindex])
swap(pq[back],pq[fatherindex]);
back=fatherindex;
fatherindex=back/2;
}
}
//bubbledown function
void bubbledown(int pq[], int front, int back){
int fatherindex=front,kidindex;
while(2*fatherindex+1 <= back){
kidindex=2*fatherindex+1;
if((kidindex+1<back) && (pq[kidindex]<pq[kidindex+1])){
kidindex++;
}
if(pq[fatherindex] > pq[kidindex]){
swap(pq[fatherindex],pq[kidindex]);
fatherindex=kidindex;
}
else
return;
}
}
//swap function
void swap(int &a, int &b){
int t=a;
a=b;
b=t;
}
A few problems to look at
You don't initialize size before using it, so your pq memory could be any size at all.
You are using 1-based access to your arrays, so make sure you allocate one more than you need.
while(!back==0) will work, but it is doing boolean logic on an int, then comparing the result with an int. while(back!=0) is a lot easier to read and will produce fewer compiler warnings.
Edit: also your bubbleDown function has an infinite loop when neither if test is triggered.

Command prompt undefined reference to everything

I am trying to build an application which takes the users input, puts it into a vector/database, and outputs the results. When I input the code into my windows command prompt compiler it just get it gives me a path C:/users/app/data/local/temp and then an undefined reference error to practically everything,cin,cout etc. It was initially only giving me the usual errors, but when I removed the errors it gave me this, whereas if I was to remove a semi-colon it would give me just one error. Any ideas on what might be causing this??
MP3.H
#define MP3_H
#include <iostream>
#include<string>
using namespace std;
class MP3
{
public:
MP3();//constructor
MP3(string,string,int,int,string);
~MP3();
string getName() const;
string getSongName() const;
int getDuration() const;
int getReleaseYear() const;
string getReview() const;
private:
string artistMP;
string songMP;
int duationMP;
int releaseyearMP;
string reviewMP;
}
#endif
MP3.cpp
#include "MP3.h"
MP3::MP3();
MP3::MP3(string artist,string song,int duration,int releaseyear,string review){
artistMP=artist;
songMP=song;
durationMP=duration;
releaseyearMP=releaseyear;
reviewMP=review;
}
~MP3::MP3();
string MP3::getName()const;{
return artistMP;
}
string MP3::getSongName()const;{
return songMP;
}
int MP3::getDuration()const;{
return durationMP;
}
int MP3::getReleaseYear()const;{
return releaseyearMP;
}
string MP3::getReview()const;{
return reviewMP;
}
main.cpp
#include<vector>
#include "MP3.h"
void fillVector(vector<MP3>&);//5
void print (const vector<MP3>&);//7
int main( )
{
vector<MP3> myRecord;
fillVector(myRecord);
print(myRecord);
return 0;
}
void fillVector(vector<MP3> & newMyRecord){//22
cout<<"How many songs in the playlist baby";
int recordSize;
cin>>recordSize;
for(int i=0;i<recordSize;i++)
{
string artist;
string song;
int duration;
int releaseyear;
string review;
cout<<"Enter Artist Name:";
cin>>artist;
cout<<"Enter Song Name:";
cin>>song;
cout<<"Enter Song Duration(in seconds):";
cin>>duration;
cout<<"Enter Release Year:";
cin>>releaseyear;
cout<<"Enter Brief Review:";
cin:review;
MP3 newMP3(artist,song,duration,releaseyear,review);
newMyRecord.push_back(newMP3);
cout<<endl;
}
cout<<endl;
}
void print (const vector<MP3>&newMyRecord)//58
{
unsigned int size = newMyRecord.size();
for (unsigned int i=0;i<size;i++){
cout<<"Artist:"<< newMyRecord[i].getName()<<endl;
cout<<"SongName:"<< newMyRecord[i].getSongName()<<endl;
cout<<"Duration:"<< newMyRecord[i].getDuration()<<endl;
cout<<"ReleaseYear:"<< newMyRecord[i].getReleaseYear()<<endl;
cout<<"Review:"<< newMyRecord[i].getReview()<<endl;
}
}
};
TIA
Building a program occurs in (at least) two stages, compilation and linking. Undefined references are linker errors. If you get linker error it implies that compilation was successful. But if you have compiler errors (e.g. bad syntax to do with semi-colons) then linking doesn't happen so you don't see any linker errors (like undefined references).