I need to make a 2D Array that can hold 5 student names (including last names) that is imputed manually by the person when asked. Now I kind of have and idea to initialize an array like this;
1 2 3 4 5
constint maxNames=5;
constint maxChar=20;
char students[maxNames][maxChar];
cout<<"Enter the names of five students:"<<endl;
That's how far I have gotten. I don't know how I would go about to accept a name and store each name in a separate row. I also need to know how I could print the names too, just so I can see if they have been stored. One more thing, I don't know how to use vectors yet, so if you know how to do this without using vectors I'd appreciate the help. Thanks in advanced.
I agree with the first couple posters that strings would be the more straightforward way to do it. But to answer your question on looping for input using a 2D array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
char sentence[5][20] ;
for ( int i = 0; i < 5; i++ )
{
cout << "\nEnter sentence: ";
cin.getline( sentence[i], 20 );
}
for ( int i = 0; i < 5; i++ )
{
cout << sentence[i] << "\n";
}
}
Loop for a line for every index of your character array. Each indice points to a string of characters (char*).
Alright I guess I made some progress haha. I was able to imput the names into the arrays, but when I "nest" loop to print the names, the names print but up to a certain point before they become some weird symbols and y's.
Sounds like your accessing memory that your program doesn't own. This happens, for example, in the following case:
1 2
char letters[5];
cout << letters[6]; //on some platforms this crashes, others is just prints garbage
What loop are you using? I don't think there is a need for any nested loops using the 2D array example... Unless you want to print one char at a time, in which case it would look something like this:
#include <iostream>
usingnamespace std;
int main()
{
char sentence[5][20];
for ( int i = 0; i < 5; i++ )
{
cout << "\nEnter sentence: ";
cin.getline( sentence[i], 20 ); //this null-terminates the array of chars by placing a '\0' at the end of the stream
}
for ( int i = 0; i < 5; i++ )
{
for ( int j = 0; j < 20; j++ )
{
//check to see if we hit the end of the string
if ( sentence[i][j] != '\0' )
cout << sentence[i][j];
else
{
cout << "\n"; //formatting
break; //stop printing past null terminator (garbage chars)
}
}
}
}
Ah wait, I ended up getting them to print! Haha thanks ......I just don't know why they would ask for a 2D array... couldn't I have just made a 1D array and go the same results??
A 1D character array would only allow you to store one "string". Each element in the array would be a character, together which would comprise your "string".
A 1D array of strings can be thought of the same thing (it's not, really) as a 2D char array, since each string object in the array of strings itself contains an array of characters.