Roxlvox Roxlvox - 1 month ago 15
C++ Question

When I try an output a 2D array it outputs the wrong numbers.

Is it my Input Output or something else that is causing the problem. I am really new to C++ so I am sorry in advance if its something simple. I have included more details about the problem inside of the code if you need some more info.

#include <iostream>
#include <iomanip>

using namespace std;

void input(string names[],int grades[][3]){
for(int n=0;n<3;n++){//Enter 3 into the grade book
cout<<"Please enter student name "<<n+1<<endl;
cin>>names[n];
}
for(int r=0;r<3;r++){// Enter 4 grades for each of the 3 students you added to the grade book
cout<<"Please enter 4 grades for "<<names[r]<<endl;
for(int c=0;c<4;c++){
cout<<"Grade "<<c+1<<": ";
cin>>grades[r][c];
}
cout<<endl;
}
}

//ignore this it wil;l be used to average the grades later
void math(int grades[][3], double average[]){

}
//If I input these number just to test the program
//student 1: 1,1,1,1
//student 2: 2,2,2,2
//student 3: 3,3,3,3
//it give me
//student 1: 1,1,1,2
//student 2: 2,2,2,3
//student 3: 3,3,3,3
void output(string names[],int grades[][3],double average[],char letter[]){
for(int r=0;r<3;r++){
cout<<names[r]<<" ";
for(int c=0;c<4;c++){
cout<<grades[r][c]<<" ";
}
cout<<endl;
}
}

int main(){

int grades[2][3];
double average[2];
char letter[2];
string names [2];

input(names,grades);
math(grades,average);
output(names,grades,average,letter);


return 0;
}

Answer

In C++, the number you use in array declaretion is not the maximum index but the number of elements.

All of your array declaration lack one element each, so allocate one more element for grades (for both dimention, including the arguments), average, letter and names.