-
searching for a record
Let's say we have something like char year [50][5] and char event [50][15] . How would I search the year array for a particular input from the user so that it would display the year and the event for what the user entered. Or display a no-match found error, if there is no record found.
-
Loop through the year array, using strcmp(). If you find a match, record the index number (eg. the iteration of the for loop). When the loop is finished test the variable to see if it contains a valid index. You could default the initial value to a number outside the range, so you can tell if the year has been found. If the variable contains a valid index print the year and corresponding event using this index number else print the not-found message.
-
I been trying to do that, expect I have no idea how to test the variable after the loop. And I end up getting the first year array record getting printed. Damn there isn't even a single example using strcmp in the book.
-
> I have no idea how to test the variable after the loop
int var=-1;
//your loop
//look up strcmp
//if match is found
//set var to index
//number
if(var==-1)
//year wasn't found
else
//print year and event
-
Well this is what I came up, but it prints out only the first year. Still confused.
cout<<"Enter the year you're searching for\n";
cin>> keyword;
for (int Index = 0;(Index < 20)&&(found ==0); Index++)
{
if(strcmp(year[Index], keyword)) {found =1;}
cout<<year[Index]<<setw(8)<<event[Index];
}
-
strcmp returns zero if the strings match.
int found=-1;
cout<<"Enter the year you're searching for\n";
cin>> keyword;
for (int Index = 0;Index < 20; Index++)
{
if(strcmp(year[Index], keyword)==0) {found =Index;}
}
if(found!=-1)
cout<<year[found]<<setw(8)<<event[found];
else
cout << "not found";
*not tested*
-
That kinda solved the problem. Though still can't make to print the error message.
Thanx a lot bro.