There is a code that searches for the keywords b and displays how many times he met them (in this case (for, while, etc.). How can you make him look for "for (), while ()" ps no matter how far stand brackets => "for (///////// - spaces)"

#include <stdio.h> #include <string.h> int Search(char line[], char word[]) { char *p; int count = 0; //start = line; while(1){ p = strstr(line, word); if(p == NULL)break; ++count; line = p + strlen(word); } return count; } int main(){ int nf = 0, nw = 0, nd = 0, ni = 0; char s[100]; FILE *fp; fp = fopen("f1.txt", "r"); while(fgets(s, 100, fp)){ nf += Search(s, "for"); nw += Search(s, "while"); nd += Search(s, "do"); ni += Search(s, "if"); } fclose(fp); printf("V file f1 vstretilos:\n"); printf("for %d raza \nwhile %d raza \ndo %d raza \nif %d raza\n", nf, nw, nd, ni); return 0; } 

Closed due to the fact that it was off topic by Nicolas Chabanovsky Jun 24 '16 at 4:14 .

  • Most likely, this question does not correspond to the subject of Stack Overflow in Russian, according to the rules described in the certificate .
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • and what the current implementation does not like? - pavel
  • it’s easy to write for what it does, although it’s not necessary, the first thing that comes to mind is to put just a space, but the matter is just in these brackets, there can be any number of spaces between the brackets, the main thing that was closed, in the right place - Zhenya
  • Well, I would then just skip all the spaces before ( and then all the characters before ) in the loop stupidly. - pavel
  • @pavel that's just something tight with the implementation) - Mar
  • bool findO = false; for ( ;*p || !findO ; p++) findO = *p == '('; if (!findO) return 0; findO = false; for ( ;*p || !findO ; p++) findO = *p == ')'; if (!findO) return 0; return 1; I think the idea further decorate. - pavel

1 answer 1

The task you described (parsing the text) is actually quite complicated. :-( For full recognition of syntactic constructions in text files, you can generate a parser using lex / yac (flex / bison).

Strongly simplifying the task and imposing a restriction, so that the opening and closing parenthesis are always on the same line, you can use

 regex (3) - POSIX regex functions 

The simplest example is where this will NOT work:

 for (j=0; j<23; // j++) { 

The difficult task is not easy to solve - alas ...