Hello guys, I need to make a program that counts the number of times a particular word appears in a text file on a line. For example, the User chooses the word "test" to be told at the end of each line of txt should show how many times that word appeared in the line. I started doing the program but I have questions regarding how this string and look. Would make str str?

Recommended Answers

All 4 Replies

hi some times people write more text i think its depend of space pepole write more text.

Would make str str?

I don't understand your question, but if you're asking whether you want to use the strstr function then the answer is yes. strstr will return a pointer to the matched string, or NULL if it wasn't found. So you can repeatedly call strstr and then skip over the match:

char *p = line;
char *match;
int n = 0;

while ((match = strstr(p, key)) != NULL) {
    /* Update the match counter */
    ++n;

    /* Skip over the match so it isn't found again */
    p = match + key_len;
}

hello again, the goal of the program has changed. Now he has to open a text file, and look for a particular word chosen by the User. Lines containing the word should appear word_yes, lines that do not contain the word should appear word_no

#include <stdio.h>
#include <string.h>

void function(char a) 
{ 

            char nameforseach[50];   
            FILE* pr = fopen("r.txt", "a++"); 
            printf("nameforseach: ");  
            gets(nameforseach);           
            if(strstr (a, nameforseach)) 
            {
                fprintf(pr, " %s %s_yes", a, nameforseach); 
            }    
            else
            {
                fprintf(pr, " %s %s_no", a, nameforseach); 
            }    
            fclose(pr);     
}


int main()  
{   
    char name[30];     
    printf("name: ");  
    gets(name);
    FILE* p = fopen(name, "r");  
    if(p)    
    {
        char test[1000000];   
        while
        (
            fscanf(p, "%s", &test) == 1  
        )
        function(test); 
        fclose(p); 
    }
    else 
         printf("\nwas not possible to open %s", name);
    printf("\n Press enter ... ");
    fflush(stdout);
    getchar();
    return 0;
}

what's wrong? =/

Not &test with fscanf, just test.

char arrays don't require an ampersand, like numeric variables do

If you have other problems, specify what they are.

Note that gets(), while it's very convenient, is totally unsafe from buffer overflow, and has been removed from the accepted C standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.