Just one question, how to add space end of string?

I'll try to explain my code. He look up words in a text, so that it stores each line. The problem is that if the word is at the end of the sentence, it does not recognize. Because it does the following, it is sought as the word "word " (the word plus a space), to differentiate word! = wordblabla. So I need to add at the end of each line space. For if the word is to look at the end of the sentence, he also recognizes.

Can't help you until you show us the code that stores the words. It could be as simple as strcat(word," ");, but might not too. It all depends on how you wrote the code.

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


int main()   
{   
    char name[30];     
    char nameforseach[100];
    char string3[10000];
    int count = 0;
    int count1 = 0;
    printf("File: ");  
    gets(name);                             
    FILE* p = fopen(name, "r");  
    printf("name for seach: ");
    gets(nameforseach);
    strcat(nameforseach," ");
    if(p)   
    {

        while(fgets(string3, sizeof(string3), p) != NULL )
        {
           if( strstr(string3, nameforseach))
              count++;                                   
        }    
        fclose(p); 
        printf("yes: %d", count);

    }
    else 
         printf("\nNot open %s", name);
    printf("\nOk, press enter!!!");     
    getchar();
    return 0;
}

example file for reading

rice cook nice
nice
nice soap

If the User place to look "nice", it will return only one. Because the first and second phrase, the word is at the end.

You need to remove the newline char that fgets() always adds to the end of the string it receives.

Nice actually looks like this, when it's the last word in the string: "nice\n\0". And what you are searching for is "nice\0".

So a bit of code for inside the for loop, before the strstr call (say line 23 above).

int len=strlen(string3)-1;
if(string3[len]=='\n')
   string3[len]='\0'; //overwriting the newline char

And try it now!

Note that a string with "nice nice nice" will show only one "nice", because you are only testing the string3 string one time - not until the string has been exhausted by the strstr search.

Edited 3 Years Ago by Adak

This article has been dead for over six months. Start a new discussion instead.