0
Guys I’m trying to make a program that counts the number of ifs in any text, but for some reason it doesn’t count all, if you can help me thank you
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE *arq;
char str[24];
int count = 0;
arq = fopen("texto.txt","r+");
while(fgets(str,sizeof(str),arq) != NULL){
if(strstr(str,"if") != NULL){
count++;
}
}
fclose(arq);
printf("Qt : %i",count);
}
Contents of "text.txt"
1 if if if if
2 if if if if if if if if
3 if if if if if if if if if if if if
4 if if if if if if if if if if if if if if if if
total = 40
When I run the program only 8 are shown.
Hello, can you share where you got that logic? I tested your code and now it reads normally, but I changed only one line and I would like to understand better how this logic works.
– Brewerton Santos
The way you declared your string
str
you need to make another loop to count on each string you read. For example line 4 contains 49 characters.– anonimo
By chance the application of this algorithm would be to calculate the cyclomatic complexity of a particular code ?
– Lacobus
@anonymity, the answer to that is no, vain is necessary.
– Brewerton Santos
@Brewerton: But the function
strstr
always part of the beginning of the string. In the example of the post it counts only the first occurrence of each line read, as it declared str[24] and there are lines with more than 24 characters to functionfgets
makes several readings of such lines. I believe the functionstrtok
is that the pointer varies at each location.– anonimo