How do I count the number of words in a text in C?

0

I have to do the following exercise:

  

Enter a character text using the function getchar( ) . Indicate the number of characters, words, and lines that form it. Show the order with explanatory signs. Consider as separators of valid words: space, tab and enter and keep in mind that counting words is not counting the number of separators. The entered text may contain any type of characters, including the enter.

The problem is that when I execute what I did, I get the following error:

invalid conversion from 'char' to 'const char*' 

I would like to know how to solve it and if it is well stated the way I did to tell the words of the text. Thanks

#include <iostream>

using namespace std;

int cantpalabras(char *);

int main()
{
    int longcarac,cantp;
    char text;

    printf ("Ingrese el texto \n");
    text=getchar();
    longcarac=strlen(text);
    cantp=cantpalabras(text);
    printf ("La cantidad de palabras es: %d \n", cantp);

    system("PAUSE");
    return 0;
}


int cantpalabras(char *at)
{
    int cont=0;
    int *punt=at;
    while (*punt)
    { if (*punt='\n'||*punt='\t')
      { cont=cont+1;
        punt++; } }

    return cont; }
    
asked by Maca Igoillo 23.01.2017 в 21:16
source

1 answer

3

A small criticism, with a constructive spirit: I recommend that you read the documentation of the functions you use or want to use:

  

size_t strlen (const char * s);

     

Returns the length of the string pointed to by s, excluding 0 from the end of the string.

With this in mind, let's see your code:

char text;
text = getchar();
...
longcarac = strlen( text );

Clearly, you can not use strlen( ) in individual characters , only in pointers to strings .

Also, if we look

  

int getchar (void);

     

Read the following character from 'stdin' and return it as an 'unsigned char' promoted to 'int'. In case of error or END OF FILE, returns EOF.

Clearly, your code will not work ; you only read 1 character, not the text that you are requested. You should make a loop, keep a string with the text, add the characters, ...

    
answered by 23.01.2017 / 21:29
source