Monday, May 24, 2010

C++ problem involving searching a text file for a user inputed word.?

Alright this is the problem....


Write a C++ program to search a file for all occurrences of the specified pattern and display the matched word together with the line number. The pattern to be searched and the name of the input file will be entered by the user from the command line.





Im pretty stuck on it... this is what i have so far, can someone give me some direction/guidence?





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;





using namespace std;


#define SIZE 500





int main(int abc , char *pattern[])


{


int cnt = 1; char line[SIZE +1];





if(abc != 3)


{


cerr %26lt;%26lt; "\nSynopis: " %26lt;%26lt; pattern[0] %26lt;%26lt; " pattern inputfile" %26lt;%26lt; endl;


return 1;


}





ifstream infile(pattern[2]);


if (infile.fail())


{


cerr %26lt;%26lt; "Cannot open file" %26lt;%26lt; endl;


return 1;


}


while(! infile.eof())


{


infile.get(line, SIZE);


if(strcmp(line, pattern[1]))


{


cout %26lt;%26lt; line %26lt;%26lt; endl;


cout %26lt;%26lt; "Line " %26lt;%26lt; cnt %26lt;%26lt; ": " %26lt;%26lt; endl;


}


++ cnt;


}


return 0;


}





Thanks...

C++ problem involving searching a text file for a user inputed word.?
It looks like the main problem with what you have so far is that your strcmp call will only find a match if the ONLY thing on the line is your pattern. It will never find the pattern within a line that contains other stuff.





You will essentially have to search every character of each line that could match the pattern. Something like this:





while (!infile.eof())


{


infile.get(line, SIZE);


for (int j=0; j %26lt; strlen(line) - strlen(pattern[1]), ++j)


{


if (strncmp(line+j, pattern[1], strlen(pattern[1]))


{


cout %26lt;%26lt; line %26lt;%26lt; endl;


cout %26lt;%26lt; "Line " %26lt;%26lt; cnt %26lt;%26lt; endl


}


++cnt;


}





Something like that.

verbena

No comments:

Post a Comment