-
arrays
I'm having trouble trying to figure out how to list these names with the first name first and the last name second without the comma. Hopefully someone can help me with this one! Any help will be greatly appreciated. Thanks, Zeni3773
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getdata();
void sortThem();
void swapThem();
void showIt();
char lname[25][35],fname[25][35];
int i=-1,j,num;
string Lname[25],Fname[25];
void main()
{
getdata();
sortThem();
showIt();
}
void getdata()
{
ifstream x;
x.open("namesid.txt");
while(!x.eof())
{
i++;
x>>Lname[i];x>>Fname[i];
cout<<Lname[i]<<" "<<Fname[i]<<endl;
}
num = i+1;
}
void sortThem()
{
cout<<endl<<endl;
for(i=0; i<=num; i++)
{
for(j=i; j<=num; j++)
{
if(Lname[i]>Lname[j])
swapThem();
}
}
}
void swapThem()
{
string temp;
temp = Lname[j];
Lname[j] = Lname[i];
Lname[i] = temp;
temp = Fname[j];
Fname[j] = Fname[i];
Fname[i] = temp;
}
void showIt()
{
cout<<endl<<endl;
for(i=0; i<=num; i++)
cout<<Lname[i]<<" "<<Fname[i]<<endl;
}
Tagged by Salem
-
me no see no comma nowhere.
The sort function looks like a bubble sort that didn't get set up correctly. In addition <= num will over read the array--use just < num.
for(i = 0; i < num; i++)//how many times to run the next loop
{
for(j = 0; j < num - 1 - i; j++)
{
if(Lname[j] > Lname[j + 1])//compare two adjacent members
//bubble the larger one up by swapping them if the if is true
BTW, i know it isn't the focus of your post, but improve your coding style avoid void main() and try to keep global variables to a minimum.
-
You also don't appear to intialize num.
-
You also forgot to put your code tags in there.
-
Thank you all for your help!! Sorry about the code tags.
zeni3773