Chaine de caractére ca ne marche pas lors de l'execution
avenger10
Messages postés
2
Statut
Membre
-
fiddy Messages postés 11653 Statut Contributeur -
fiddy Messages postés 11653 Statut Contributeur -
Bonjour,
#include<string.h>
#include <stdio.h>
void main()
{
int x;
char ch1[10];
char ch2[10];
char ch3[10];
printf("donner votre chaine");
gets (ch1);
printf("donner votre chaine");
gets (ch2);
x=strstr(ch1,ch2);
printf("%d",x);
}
#include<string.h>
#include <stdio.h>
void main()
{
int x;
char ch1[10];
char ch2[10];
char ch3[10];
printf("donner votre chaine");
gets (ch1);
printf("donner votre chaine");
gets (ch2);
x=strstr(ch1,ch2);
printf("%d",x);
}
A voir également:
- Chaine de caractére ca ne marche pas lors de l'execution
- Caractère ascii - Guide
- Caractère spéciaux - Guide
- Recherche automatique des chaînes ne fonctionne pas - Guide
- Caractere speciaux - Guide
- Caractere vide - 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;
}
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; }