Two Plus Two Newer Archives

Two Plus Two Newer Archives (http://archives1.twoplustwo.com/index.php)
-   Computer Technical Help (http://archives1.twoplustwo.com/forumdisplay.php?f=50)
-   -   PLEASE Help Me With Simple C++ Code! (http://archives1.twoplustwo.com/showthread.php?t=544478)

DeadlyGambit 11-12-2007 05:31 PM

PLEASE Help Me With Simple C++ Code!
 
Okay I have to search a large text file for instances of a user-entered string. I did this using the find function, and it works properly. Here is the problem, I can only find the FIRST occurance of the specified string within any giving line. (I'm searching line by line here, using getline to read lines from the file, and then using find function to find string.) But I need to find ALL instances of the specified string within each line. As of now, it just stops when it finds the first instance within each line.

Example (this is actually the 1st line of text in the file):
Say the search phrase is "hate me "

"5 meg file hate me hate me hate men gg hate merry"

this would result in "hate me" being counted 4 times on that line
("hate me " only twice)

Nemesis69 11-12-2007 05:42 PM

Re: PLEASE Help Me With Simple C++ Code!
 
See on which index of the string that word is found. Then make a substring of the sentence from where the word ends (index + length word) till the end of sentance and use find again?

psionic storm 11-12-2007 06:06 PM

Re: PLEASE Help Me With Simple C++ Code!
 
you can do that with a loop.

c libraries are online and well documented btw.
http://www-ccs.ucsd.edu/c/string.html

pokergrader 11-13-2007 02:36 AM

Re: PLEASE Help Me With Simple C++ Code!
 
Don't mess with C stuff. Use the C++ string class, especially the find(string, index) function.

Sample code to get you started:
<font class="small">Code:</font><hr /><pre>
string a = "5 meg file hate me hate me hate men gg hate merry";
cout &lt;&lt; a.find("hate me",0) &lt;&lt; "\n";
cout &lt;&lt; a.find("hate me",20) &lt;&lt; "\n";
</pre><hr />

fiskebent 11-13-2007 12:39 PM

Re: PLEASE Help Me With Simple C++ Code!
 
I like C...

<font class="small">Code:</font><hr /><pre>#include &lt;string.h&gt;
#include &lt;stdio.h&gt;

void main(int argc, char *argv[])
{
FILE *f;
int found = 0;
char *position;
char line[300];
f = fopen(argv[1], "r");
while (fgets(line, sizeof(line), f)) {
position = line;
while (position = strstr(position++, "hate me")) {
found++;
}
}
fclose(f);
printf ("\"hate me\" found %d times.\n", found);
}</pre><hr />


All times are GMT -4. The time now is 06:55 PM.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.