for(int i = 0; i<5; i++)
if(strcmp(collection[i].albumName, albumName)==0)
{
location = i;break;
}
That's a good way to confuse the hell out of readers and introduce subtle scoping bugs. My general guideline for blocks with optional braces is that if there's a one line statement, you can go ahead with the omission. If the block has more than one line, including comments, use braces. So your code would be:
for(int i = 0; i<5; i++)
{
if(strcmp(collection[i].albumName, albumName)==0)
{
location = i;break;
}
}
Of course, that brings me to the real error, which is using strcmp with std::string objects. Not such a hot idea, especially since the string class overloads the == operator for comparison. I'm guessing you didn't compile that code.
if (location != -1)
{
cout<<"Album name is:"<<collection[i].albumName<<" "<<collection[i].artistName<<"at"<<location<<".";
return location;
}
else return -1;
I think you fell into the trap that I described above. The second if statement isn't inside the loop. The code shouldn't compile because i isn't visible anymore.
On top of that, you've complicated the function a little too much. It could be as simple as this:
int search ( Album collection[], int size, string albumName )
{
for ( int i = 0; i < size; i++ ) {
if ( collection[i].albumName == albumName )
return i;
}
return -1;
}
And of course, unless you know for a fact that your code will compile and run as expected (which I do in this case), you should write a test framework. Something like so:
int main()
{
Album collection[5];
collection[0].albumName = "Private Investigations1";
collection[1].albumName = "Private Investigations2";
collection[2].albumName = "Private Investigations3";
collection[3].albumName = "Private Investigations4";
collection[4].albumName = "Private Investigations5";
cout<< search ( collection, 5, "Private Investigations1" ) <<'\n';
cout<< search ( collection, 5, "Private Investigations2" ) <<'\n';
cout<< search ( collection, 5, "Private Investigations3" ) <<'\n';
cout<< search ( collection, 5, "Private Investigations4" ) <<'\n';
cout<< search ( collection, 5, "Private Investigations5" ) <<'\n';
cout<< search ( collection, 5, "Private Investigations" ) <<'\n';
}