-1
I have a problem in the project, this code should count the lines and words of a text file in C but the output of the number of lines is right and the number of words is always 0.
//Função que conta as palavras de uma linha
int palavras(char *line)
{
int p = 0, j;
char *str = "\t\r\n\v\f";
char *saveptr1, *str1, *token;
line[strlen(line) - 1] = '\0';
for (j = 1, str = line; j++, str1 = NULL ;)
{
token = strtok_r(str1, str, &saveptr1);
if (token==NULL) break;
p++;
}
return p;
}
// Resto do programa
int palavras(char[]);
int main(int argc, char *argv[])
{
FILE * fp;
ssize_t n = 0;
int nlinhas = 0, p = 0;
char * line = NULL;
fp = fopen(argv[1], "r");
exit_on_null(fp, "Erro na abertura");
while ((n = getline(&line, &n, fp)) != -1)
{
line[strlen(line) - 1]='\0'; /
p = palavras(line);
nlinhas++;
}
printf("Número de Linhas: %i\n",nlinhas);
printf("Número de Palavras: %i\n",p);
if (line) free(line);
fclose(fp);
return 0;
}
Take a look at it:
for(j=1,str=line;j++,str1=NULL;)
because you put the increment together with the condition of ending the loop. It also seems to me that you mixed the use of str and str1 since you initialize str with the separator characters (missing space) but point to the string received by parameter.– anonimo
The problem is that when I compile the code tells me that I expect a ; before the token ) like this: error: expected ?;' before ?)' token for(j=1,str1=line;j++,str1=NULL).
– Vort3x
Review your command for, it makes no sense. Why these assignments?
– anonimo
I want you to go through each line (j being the number of lines) and use the string that comes from the line and then using the strtok_r function to see if it counts as a word or not.
– Vort3x