Question

I've tried using both binary search, and while loops and for loops in my searches and the same problem is occurring.

When my original program comes to this function call, the linear search function (displayContent) will always assign -1 to position, and after the function call the program breaks and exits.

I have tried to rearrange my program. Like I said, I tried for loops and while loops with both binary and linear search.

I am also using a structure data type of

struct info
{
    string name;
    double score[5];
    double avg;
};

Here is my function call

cout<<"Please enter the name of the person which you would like to search. ";
getline(cin, name);
cin.ignore();
displayContent(contestant, count, name);

Here is my function definition

void displayContent(info contest[], int quantity, string id)
{
int position=-1;
bool found=false;

for(int index=0;index<quantity && !found;index++)
{
    if(contest[index].name.compare(id)==0)
    {
        found=true;
        position=index;
    }
}
    if(position==-1)
    {
        cout<<"That person was not one of the contestants.";
    }
    else
    {
        cout<<"The scores for "<<contest[position].name<<" are \n     Contestant     Judge1  Judge2  Judge3  Judge4  Judge5  Average"
            <<"\n______________________________________________________________________"<<endl;
        cout<<right<<setw(15)<<fixed<<setprecision(1)    <<contest[position].name<<setw(10)<<contest[position].score[0]<<setw(8)<<contest[position].score[1]<<setw(8)<<contest[position].score[2]<<setw(8)<<contest[position].score[3]
        <<setw(8)<<contest[position].score[4]<<setw(8)<<contest[position].avg<<endl;
    }
}
Was it helpful?

Solution

Have you verified that getline does what you expect? Perhaps name contains a line ending character. To rule out problems with input you can try to assign a value to name you know exists in contestant before calling displayContent.

I haven't been able to spot any problems in your search algorithm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top