So, I'm working on an assignment. It involves a read-in text file and the program itself. When I run it I get what my teacher would call "garbage" in the output.
Here is the info from the .txt:
Mike 1200
John 350
Jen 1500
Tara 700
Michelle 2000
Kevin 500
Matt 450
Kim 200
..and here is my source code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void OrderByName(string[], float[], int);
void OrderByScore(string[], float[], int);
int SearchForWinner(string[], float[], int);
int main()
{
string name[15];
string search;
float score[15];
int count =0;
ifstream infile("winners.txt");
if(!infile)
{
cout << "unable to open file , so exiting from program ";
return 0;
}
while(!infile.eof())
{
infile >> name[count] >> score[count];
count++;
}
//OrderByName(name, score, count);
OrderByScore(name, score, count);
SearchForWinner(name,score,count);
infile.close();
return 0;
}
void OrderByName(string array[], float score[], int n)
{
cout<< " Ordered alphebetically by name:\n";
for(int i=0; i<n; i++)
{
int min = i;
for(int j=i; j<n; j++)
{
if(array[min]>array[j])
{
min = j;
}
}
string temp = array[i];
array[i] = array[min];
array[min] = temp;
float temp1 = score[i];
score[i] = score[min];
score[min] = temp1;
cout<<array[i]<<" "<<score[i]<<endl;
}
}
//cout<< " Ordered alphebetically: "<<temp1 " "<<score<<endl;
void OrderByScore(string array[], float score[], int n)
{
cout<<" Ordered by Score: "<<endl;
for(int i=0; i<n; i++)
{
int min = i;
for(int j=i; j<n; j++)
{
if(score[min]>score[j])
{
min = j;
}
}
string temp = array[i];
array[i] = array[min];
array[min] = temp;
float temp1 = score[i];
score[i] = score[min];
score[min] = temp1;
cout<<score[i]<<" "<<array[i]<<endl;
}
}
int SearchForWinner(string array[], float score[], int n)
{
OrderByName(array,score,n);
string search;
cout << "Enter a name: ";
cin >> search;
int start = 0;
int end = n - 1;
int index = 0;
int middle = (start+end)/2;
while( start <= end )
{
if ( array[middle] < search )
start = middle + 1;
else if ( array[middle] == search )
{
index = middle;
break;
}
else
end = middle - 1;
middle = (start + end)/2;
}
if(start > end)
index = -1;
if(index>0)
cout << search << " is in the list and resides in position " <<(index/*+1*/) << " alphabetically. "<< endl;
else
cout << search << " was not found in the list. " << endl;
return index;
}
When I run it, I get this:
Ordered by Score:
3.98864e-34 //here is the garbage I'm talking about!
200 Kim
350 John
450 Matt
500 Kevin
700 Tara
1200 Mike
1500 Jen
2000 Michelle
Ordered alphebetically by name:
3.98864e-34 //here is the garbage I'm talking about!
Jen 1500
John 350
Kevin 500
Kim 200
Matt 450
Michelle 2000
Mike 1200
Tara 700
Enter a name:
I commented where the unwanted output is. I've run into this before, but since I can't remember how to fix it, I guess I didn't learn it.