Hi. im having a problem with 2 dimensional array.
im assigned to read the input of 45 names with corresponding gender, then display then and the number of males and females.
so far i got:
#include<iostream>
using namespace std;
int main()
{
char sname[45][4],row;
int male=0,female=0;
for (row=0;row<45;row++)
{
cout<<"\nEnter Last name: ";
cin>>sname[row][1];
cout<<"Enter First name: ";
cin>>sname[row][2];
cout<<"Enter mi: ";
cin>>sname[row][3];
cout<<"Enter gender: ";
cin>>sname[row][4];
do{
if (sname[row][4]=='m'||sname[row][4]=='M')
male++;
else if (sname[row][4]=='f'||sname[row][4]=='F')
female++;
else
cout<<"Invalid gende. Enter again.";
}while (sname[row][4]=='m'||sname[row][4]=='M'||sname[row][4]=='f'||sname[row][4]=='F');
}
row=0;
for (row=0;row<45;row++)
{
cout<<sname[row][1]<<", "<<sname[row][2]<<" "<<sname[row][3]<<" \n";
}
return 0;
}
but when i type more than 1 character the program passes the name codes as the number of character i typed...
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string sname[45][4]; //changed from a array of char to an array of strings
int row=0, male=0,female=0; //row should be an int not a char
for (row=0;row<45;row++)
{
cout<<"\nEnter Last name: ";
cin>>sname[row][1];
cout<<"Enter First name: ";
cin>>sname[row][2];
cout<<"Enter mi: ";
cin>>sname[row][3];
cout<<"Enter gender: ";
cin>>sname[row][4];
do{
if (sname[row][4]=="m"||sname[row][4]=="M") // changed character literals('') to string literals ("")
male++;
elseif (sname[row][4]=="f"||sname[row][4]=="F")
female++;
else
cout<<"Invalid gende. Enter again.";
}while (sname[row][4]=="m"||sname[row][4]=="M"||sname[row][4]=="f"||sname[row][4]=="F");
}
row=0;
for (row=0;row<45;row++)
{
cout<<sname[row][1]<<", "<<sname[row][2]<<" "<<sname[row][3]<<" \n";
}
return 0;
}
It looks like you need to put the cin>>sname[row][4]; inside the do...while loop, as it is the user does not get to enter a different gender if it is incorrect. Plus the logic is slightly wrong, you only want it to stay in the loop if those conditions are not true. e.g. }while (!(sname[row][4]=="m"||sname[row][4]=="M"||sname[row][4]=="f"||sname[row][4]=="F"));