-
keyword searching in C
i made this program to search for a keyword but it doesnt seem towork coz it always give me the not found!msg though i know the word exists!pls help me what s wrong with my program???
int find(arrGame aGame)
{
int nCtr,i,j,k,l,m,nVal;
str70 strTemp;
char sKey[31];
int nFound=0,nWhere;
nCtr =0;
do{printf("\n\n Enter Keyword:>");
scanf("%s",sKey);
if(strlen(sKey)>31)
printf("Keyword must only be 30 characters or less");
}while(strlen(sKey)>31);
if(sKey[0]=='\0')
return(NOT_FOUND);
else
while(nCtr<MAX)
{
while(strcmp(aGame[nCtr].strQuestions,""))
{
for(j=0;j<strlen(aGame[nCtr].strQuestions);j++)
{nVal=j;
for(m=0;m<strlen(sKey);m++)
{strTemp[j]=aGame[nCtr].strQuestions[nVal];
nVal++;
}
strTemp[j]='\0';
if(!strcmp(aGame[nCtr].strQuestions,sKey))
{
nFound=1;
return(nCtr);
}
else
nCtr++;
}
}
if(nFound==1)
nWhere=nCtr;
else
nWhere=NOT_FOUND;
return(nWhere);
}
}
/*Function: view_Keyword(arrGame,int) *
* Purpose: this function displays the question matching the keyword *
* Note: Calls the function int find() */
void view_Keyword(arrGame aGame,int i)
{
int nNum,nChoice;
do
{printf("\n ~ ~ ~ ~ ~ VIEW KEYWORD ~ ~ ~ ~ ~ \n");
nNum = find(aGame);
if( nNum==-1)
printf("not found!");
else
display_Question(aGame,nNum);
printf(" Would you like to look up another(1-yes/0-no)?");
scanf("%d",&nChoice);
if(nChoice==1)
view_Keyword(aGame,i);
else if(nChoice==0)
view_Question(aGame);
else
puts(ERROR);
}while(nChoice==1);
}
-
Please include the definitions of any types you post, so we know exactly what teh code means. In this case, I'm talking about the type "arrGame" and "str70"
MAX?
I'm sorry, but this can't be done without seeing the #defines and typedefs.
-
As for protecting your string for now use
scanf("%30s",char_array_name);
because it the user overwrites the string even once, the program has done irreparable damage. This at least prevents that, but ofcourse there are even better solutions such as fgets.
fgets(char_array_name, 30, stdin);
But the problem with fgets is that it will leave a newline character in the string so you have to take it out yourself.
char_array_name[ strlen(char_array_name) - 1] = '\0';
And yes you can also top this by designing your own string class, but it's a lot more work.
Also, when you compare strings, if the result is zero than they are equal.
if ( strcmp(string_1,string_2) == 0) { ...do this }