1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define LG_TAMPON 32
enum Etats
{
MOT_DEHORS,
MOT_DEDANS
};
void fclean(char *p_tampon, FILE *fp);
size_t compter_mots(char const * const p_tampon);
int main(void)
{
char tampon[LG_TAMPON] = "";
size_t n_mots = 0;
printf("Entrez une phrase (%d caractères max): ", LG_TAMPON - 2);
fflush(stdout);
fgets(tampon, sizeof tampon, stdin);
fclean(tampon, stdin);
n_mots = compter_mots(tampon);
printf("Votre phrase se compose de %u mot%s\n", (unsigned int) n_mots,
(n_mots > 1) ? "s":"");
return EXIT_SUCCESS;
}
/**
* Compte les mots contenus dans un tampon.
*/
size_t compter_mots(char const * const p_tampon)
{
int compteur = 0;
if (p_tampon != NULL)
{
enum Etats etat = MOT_DEHORS;
size_t i;
for (i = 0; p_tampon[i] != '\0'; i++)
{
if (!isspace(p_tampon[i]) && etat == MOT_DEHORS)
{
compteur++;
etat = MOT_DEDANS;
}
else if (isspace(p_tampon[i]) && etat == MOT_DEDANS)
{
etat = MOT_DEHORS;
}
}
}
return compteur;
}
/**
* Fais le menage apres utilisation de fgets().
*/
void fclean(char *p_tampon, FILE *fp)
{
if (p_tampon != NULL && fp != NULL)
{
char *pc = strchr(p_tampon, '\n');
if (pc != NULL)
{
*pc = 0;
}
else
{
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF)
{
}
}
}
} |
Partager