-
2D array output help
Hi, I am new to C++ and in need of a little help.
I am trying to output a two dimension array of student names, "n[][30]". The names that are being inputed are: Corey, David, Kacey, Terry
The code I have at the moment is:
#define STUDENTCOUNT 4
.
.
.
.
cout << "Name" << endl;
for(int i = 0; i < STUDENTCOUNT; i++)
{
cout << n[i][30] << " \n";
}
The output that I get is
Name
D
K
T
8
Any ideas on why I am getting this output would be appreciated.
-
Basicallly you are only outputting one character of each of the names and not all of them.
n[i][30] only points to one character (the 30th) in each of names. And as the names dont fill up all the 30 allocated characters the empty spaces contain garbage. Thats why you are getting the 8 printed.
To remedy you would create another for loop that seqeunces through the 30 characters in each element.
eg.
for(int i = 0; i < STUDENTCOUNT; i++)
{
for(int j = 0; j < 30; j++)
{
cout << n[i][j];
}
count << "/n";
}
-
Thanks for that help, now it will print the whole name, but it's also printing garbage in between the names.
I tried playing with the /n escape sequence, but all I got were the names one character per line, and garbage in between
How would I get to the next line after I input a name thats less than the 30 allocated spaces, without getting all that extra garbage in between.
Right now im getting
Name
Corey[|[|[|[|[|[|David[|[|[|[|[|[|Kacey[|[|[|[|[|[|[|[|[|Terry
the output should be
Name:
Corey
David
Kacey
Terry
-
you should be able to display the name entirely instead of character by character, just drop off the second dimention.
for(int i = 0; i < STUDENTCOUNT; i++)
{
cout << n[i] << " \n";
}
ofcourse each string needs to be null terminated, but depending on how you input the name they already are
this method works because of the relationship between character arrays and pointers :) I haven't felt like bothering with the non-basic complexities of pointers yet, so if someone would like to explain exactly how this work then feel free :D
-
AH HA!
That got it working. Thanks for the help guys, it is truly appreciated.
Being a newbie, truly sucks.
So if I am understanding correctly, since the inputing of the names was null terminated upon entering them, the second dimension is not needed for the outputing.
Hence the unused character spaces were represented as garbage.
-
actually i think it has more to do with pointers, but all character arrays(strings) should be null terminated. the null character (\0) is very useful because it marks the end of a string.
I can't explain it too well because i'm still a newbie myself, well more like a newbie lvl 2 ;) i think next i'll learn more about pointers and pointer notation. I'm sure it'll help with classes.