Printing arrays using for loop in C++ - c++

I'm trying to print the value of pointer array using for loop as usual, and I managed to print value stored in one object, but can't print the value stored in another object. My classes are defined in Predmet.h:
#include <iostream>
#include <string>
using namespace std;
class Predmet
{
public:
int numberOfItems;
string name;
Predmet();
~Predmet();
};
and Plaza.h:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
My main.cpp looks like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include "Plaza.h"
#include "Predmet.h"
using namespace std;
int main() {
int n, m;
int *numberOfBeaches;
Plaza *obj1;
Predmet *obj2;
cout << "Enter number of beaches (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length and coordinates for " << i + 1 << ". beach: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
cout << endl;
cout << "Enter number of items (M): ";
cin >> m;
obj2 = new Predmet[m];
numberOfBeaches = new int[n];
for (int i = 0; i < m; i++) {
cout << "Enter ordinal number of beach for " << i + 1 << ". item: ";
cin >> numberOfBeaches[i];
cout << "Enter how much of item you have and name of the item: ";
cin >> obj2[i].numberOfItems >> obj2[i].name;
}
int *p;
for (int i = 0; i < n; i++) {
p = find(numberOfBeaches, numberOfBeaches + n, i + 1);
if (*p == i + 1) {
for (int j = 0; j < m; j++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << obj2[j].numberOfItems << " " << obj2[j].name << endl;
}
}
else {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << endl;
}
}
delete[] obj1;
delete[] obj2;
delete[] numberOfBeaches;
system("pause");
return 0;
}
Everything was working until this point where I add printing for obj2[i].kolicina and obj2[i].opis, I get weird looking result as a print and this exception thrown, as you can see below:
What am I doing wrong? Thanks in advance.
EDIT:
After suggestions in the comments, I managed to fix the code (updated version above) to print it proper way, only when I have M > 1 (e.g. M = 2) I get duplicate printing of lines? How can I fix that?

The problem is with this line:
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].duljina << " - predmeti: " << obj2[i].kolicina << " " << obj2[i].opis << endl;
obj2 is being defined as having m elements, yet you are using i, which has the values 0 <= i < n. I don't know what m's relation is to n, but that is certainly where you should start.

obj2contains melements:
obj2 = new Predmet[m];
brojPlaze contains n elements:
brojPlaze = new int[n];
you are looping over all Predmet in obj2:
for (int i = 0; i < m; i++) {
...
}
and inside the loop, you access element i of brojPlaze:
cin >> brojPlaze[i];
but i goes from 0 to m, and m can be greater than the n element brojPlaze contains. thus, you may access an element outside of the array, which can cause a lot of undesired effects...

Related

How do i add up my array values and display it along side with my other values

I am trying to add up all the values that have been stored into array b and have it display under the "total column" and don't know how to only have the scores add together.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
int sum = 0;
cout<<"Enter grades for 4 exams for the 5 students \n";
for(int i=0;i<5;i++)
{
for(int b=1;b<=4;b++)
{
cout <<setw(8)<< "enter student "<< i << "'s grade for exam " << b << '\n';
cin >> array[i][b];
}
}
cout <<"ID"<<setw(11)<<"score 1"<<setw(11)<<"score 2"<<setw(11)<<"score 3"<<setw(11)<<"score 4"<<setw(11)<<"total"<<setw(11)<<"letter"<<endl;
cout <<"--------------------------------------------------------------------------------------------------------------\n";
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
}
cout <<"--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
To be more specific around line 28
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
Arrays indexes start at 0, not 1. You are correctly looping through your array's 1st dimension, but not its 2nd dimension. You need to change the inner for loops from for(int b=1;b<=4;b++) to for(int b=0;b<4;b++)
Also, to handle the total column, you simply need to reset sum to 0 on each iteration of the 1st dimension, and then print the result after the iteration of the 2nd dimension.
Try this:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
cout << "Enter grades for 4 exams for the 5 students \n";
for(int i = 0; i < 5; i++)
{
for(int b = 0; b < 4; b++)
{
cout << "Enter student " << i+1 << "'s grade for exam " << b+1 << '\n';
cin >> array[i][b];
}
}
cout << "ID" << setw(11) << "score 1" << setw(11) << "score 2" << setw(11) << "score 3" << setw(11) << "score 4" << setw(11) << "total" << setw(11) << "letter" << endl;
cout << "--------------------------------------------------------------------------------------------------------------\n";
for(int i = 0; i < 5; i++)
{
cout << setw(2) << left << i+1 << right;
int sum = 0;
for(int b = 0; b < 4; b++)
{
sum = sum + array[i][b];
cout << setw(11) << array[i][b];
}
cout << setw(11) << sum << '\n';
}
cout << "--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
Online Demo

C++ POINTERS (student * [n] gives the error that array type is not assignable)

#include <iostream>
#include "student.h"
using namespace std;
int main()
{
// inputting the number of students
int n;
cout << "How many students would you like to process?" << endl;
cin >> n;
student* s[n];
string tmp;
double t;
// entering each student details
for (int i = 0; i < n; i++)
{
// dynamically allocating object
s[i] = new student();
cout << "Enter first name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setFirstName(tmp);
cout << "Enter middle name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setMiddleName(tmp);
cout << "Enter last name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setLastName(tmp);
cout << "Enter GPA for student " << (i + 1) << endl;
cin >> t;
s[i]->setGPA(t);
}
double avgGPA = 0;
// printing the student details
cout << "Students:" << endl;
cout << "---------" << endl
<< endl;
for (int i = 0; i < n; i++)
{
cout << s[i]->getFirstName() << " " << s[i]->getMiddleName() << " " << s[i]->getLastName() << " " << s[i]->getGPA() << endl;
avgGPA += s[i]->getGPA();
}
avgGPA /= n;
// printing the average GPA
cout << endl
<< "Average GPA: " << avgGPA;
// freeing the memory allocated to objects
for (int i = 0; i < n; i++)
delete s[i];
return 0;
}
Under the main function student * s [n]; says the array type is not assignable to the line.It also gives an error that the expression must contain a literal. I thought I was doing everything right, but there was an error. What is the solution to this error can anyone help?
student* s[n]; is a Variable-Length Array (VLA), which is not in the standard C++.
You should use std::vector like std::vector<student*> s(n);.
Also add #include <vector> at the beginning of your code to use that.

I have a question about dynamic allocation of memory in c++

I'm new to c++ and I can't understand something in dynamic allocation.
why does the following program build but gives an error and stops?
#include <iostream>
using namespace std;
int main()
{
int amount;
int *p = new int[amount];
cout << "enter the size of array" << endl;
cin >> amount;
for(int i = 0; i < amount ; i++)
{
cout << "enter the " << i + 1 << " number" << endl;
cin >> p[i];
}
for(int i = 0; i < amount ; i++)
{
cout << "number " << i + 1 << " is : " << p[i] << endl;
}
delete []p;
}
You are trying to use amount before you have assigned any value to it. You need to read the user's input for amount first, THEN allocate using it. Not the other way around.
#include <iostream>
using namespace std;
int main()
{
int amount;
cout << "enter the size of array" << endl;
cin >> amount;
int *p = new int[amount];
for(int i = 0; i < amount ; i++) {
cout << "enter the " << i + 1 << " number" << endl;
cin >> p[i];
}
for(int i = 0; i < amount ; i++) {
cout << "number " << i + 1 << " is : " << p[i] << endl;
}
delete[] p;
}

An issue with my display function

I'm working on a project for class that employs a class called employee. Where I'm having an issue is with the display function. Everything displays correctly until the end where it proceeds to output a list of symbols that eventually throwing:
exception is thrown: read access violation.
this was 0xFF4000.
I've narrowed to issue to either the display function or the loop that outputs the display. Any help with this issue would be much appreciated.
#include <iostream>
#include <iomanip>
using namespace std;
class Employee {
private:
int empcode;
char empname[10];
public:
void getdata();
void display();
};
void Employee::getdata() {
cout << "\nNAME : ";
cin >> empname;
cout << "\nCODE : ";
cin >> empcode;
}
void Employee::display() {
cout << endl << setw(20) << empname << setw(10) << empcode << endl;
}
int main()
{
Employee Emp[6];
cout << "Enter employee details:\n ";
for (int i = 0; i<6; i++)
{
cout << "\nemployee " << i + 1 << endl;
Emp[i].getdata();
}
cout << "\nEmployee details are as follows :";
cout << "\n\n" << setw(20) << "NAME" << setw(10) << "CODE";
cout << "\n------------------------------";
for (int i = 0; 1 <= 6; i++)
Emp[i].display();
return 0;
}
Your second loop is wrong:
for (int i = 0; 1 <= 6; i++)
Should be:
for (int i = 0; i < 6; i++)
1 < 6 will loop all the time, but your i++ will be increasing every iteration, when it gets 6, it tries to access to nonexistent element Emp[6], there are only Emp[0]...Emp[5]

Setiosflags is not recognized

I'm trying to compile this but I get the error error: ‘setioflags’ was not declared in this scope which sounds like its trying to recognize it as a variable. This is an example I copied straight from my textbook, checked it over several times and can't find an error. Am I overlooking something? I'm on a mac if that makes a difference, I know the <conio.h> library doesn't work because of that, but <iomanip> is recognized
#include <iostream>
#include <iomanip>
using namespace std;
const int DISTRICTS = 4;
const int MONTHS = 3;
int main() {
int d, m;
double sales[DISTRICTS][MONTHS];
cout << endl;
for(d = 0; d < DISTRICTS; d++)
for(m = 0; m < MONTHS; m++)
{
cout << "Enter sales for district " << d+1;
cout << ", month " << m+1 << ": ";
cin >> sales[d][m];
}
cout << "\n\n";
cout << " Month\n";
cout << " 1 2 3";
for(d = 0; d < DISTRICTS; d++)
{
cout << "\nDistrict " << d+1;
for(m = 0; m < MONTHS; m++) // Display array values
cout << setiosflags(ios::fixed) // Not exponential
<< setioflags(ios::showpoint) // Always use poin
<< setprecision(2) // Digits to right
<< setw(10) // Field width
<< sales[d][m]; // Get number from array
} // end for(d)
cout << endl;
return 0;
}
You're looking for setiosflags. Note the extra s in there. Your spelling is different on the second call.