Chaine de caractére ca ne marche pas lors de l'execution
Fermé
avenger10
Messages postés
2
Date d'inscription
jeudi 28 février 2013
Statut
Membre
Dernière intervention
2 mars 2013
-
28 févr. 2013 à 20:03
fiddy Messages postés 11069 Date d'inscription samedi 5 mai 2007 Statut Contributeur Dernière intervention 23 avril 2022 - 28 févr. 2013 à 22:02
fiddy Messages postés 11069 Date d'inscription samedi 5 mai 2007 Statut Contributeur Dernière intervention 23 avril 2022 - 28 févr. 2013 à 22:02
A voir également:
- Chaine de caractére ca ne marche pas lors de l'execution
- Caractère spéciaux - Guide
- Excel extraire chaine de caractère après un caractère ✓ - Forum Excel
- Caractère invisible ✓ - Forum Windows
- Caractère spéciaux mac clavier - Guide
- Caractère ascii - Guide
1 réponse
Comme il est dit dans la manpage de gets :
Never use gets(). Because it is impossible to tell without knowing the data
in advance how many characters gets() will read, and because gets() will con?
tinue to store characters past the end of the buffer, it is extremely danger?
ous to use. It has been used to break computer security. Use fgets()
instead.
Et strstr renvoie un char* on ne peux donc pas le stocker dans un int.
Exemple :
Never use gets(). Because it is impossible to tell without knowing the data
in advance how many characters gets() will read, and because gets() will con?
tinue to store characters past the end of the buffer, it is extremely danger?
ous to use. It has been used to break computer security. Use fgets()
instead.
Et strstr renvoie un char* on ne peux donc pas le stocker dans un int.
Exemple :
#include <stdio.h>
#include <string.h>
int main() {
char *p;
char ch1[10], ch2[10];
printf("Chaine 1 : ");
fgets(ch1,10,stdin);
printf("Chaine 2 : ");
fgets(ch2,10,stdin);
p = strstr(ch1,ch2);
printf("Substring : %s\n", p);
return 0;
}
28 févr. 2013 à 22:02
Il faut donc supprimer le '\n'.
J'ai donc corrigé le code :
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10 static void videBuffer(void) { int c; while ( (c = getchar()) != '\n' && c != EOF); } static char * lireChaine (char * ch, const int sz) { char *ret = fgets(ch, sz, stdin); if (ret != NULL) { char *p = strchr(ch, '\n'); if (p != NULL) { *p = '\0'; } else { videBuffer(); } } return ret; } int main(void) { char ch1[MAX], ch2[MAX]; char *p; printf("Chaine 1 : "); if (lireChaine(ch1, sizeof ch1) == NULL) { fputs("erreur de lecture\n", stderr); return EXIT_FAILURE; } printf("Chaine 2 : "); if (lireChaine(ch2, sizeof ch2) == NULL) { fputs("erreur de lecture\n", stderr); return EXIT_FAILURE; } p = strstr(ch1,ch2); if (p != NULL) { printf("Substring : %s\n", p); } else { puts("chaine non trouve"); } return 0; }