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 87 88 89 90 91 92 93 94 95
|
#include <iostream>
#include<string>
#include<math>
using namespace std;
char *mini;
int nombre_de_chiffes(unsigned int n) {
if(n<=9) return 1;
else return nombre_de_chiffes((n-n%10)/10)+1;
}
void int_to_chaine(int n,char *res){
if(n<0) {
char *q=new char[1];
int_to_chaine(-n,q);
*res='-';*(res+1)='\0';
strcat(res,q);
}
else if(n<=9) {
*res=char('0'+n);*(res+1)='\0';
}
else {
char *ch=new char[1];
int_to_chaine((n-n%10)/10,res);
int_to_chaine(n%10,ch);
strcat(res,ch);
}
}
void plus_petit_int_en_chaine() {
mini=new char[1];
int_to_chaine(-numeric_limits<int>::max(),mini);
int p=nombre_de_chiffes(numeric_limits<int>::max());
if(*(mini+p)!='9') *(mini+p)=char(*(mini+p)+1);
else {cout<<"plantage";exit(-1);}
}
bool depassement_capacite(char *c) {
char *maxi=new char[1];
int_to_chaine(numeric_limits<int>::max(),maxi);
if ( strlen(c)>strlen(maxi) ) return true;
else if ( strlen(c)<strlen(maxi) ) return false;
else if (strcmp(c,maxi)<=0) return false;
else return true;
}
char * tampon() {
const max=100;//arbitraire
cout<<"entrer un entier: ";
char *ch=new char[max];
cin.getline(ch,max);
if(!cin) {cout<<"erreur";exit(-1);}
return ch;
}
bool analyse_lexicale(char *ch,char &c) {
int lg=strlen(ch);
bool valide;
c=ch[0];int i=1;
valide=( c=='+' || c=='-' || (c>='0' && c<='9') );
while(i<lg && valide ) {
valide=(ch[i]<='9' && ch[i++]>='0');
}
return valide;
}
int lecture_entier_sans_signe(char *c) {
if(depassement_capacite(c)) {
cout<<"depassement des capacites:le plus grand int est: ";
cout<<numeric_limits<int>::max()<<endl;
exit(-1);
}
int res;int lg=strlen(c);
if(lg==1) res=c[0]-'0';
else res=(c[0]-'0')*pow(10,lg-1)+lecture_entier_sans_signe(c+1);
return res;
}
void lecture_entier(int &n) {
char *ch=tampon();
char s;
if(!analyse_lexicale(ch,s)){
cout<<"erreur de saisie."<<endl;exit(-1);
}
plus_petit_int_en_chaine() ;
if( strcmp(ch,mini)==0 ) n=numeric_limits<int>::min();
else if(s=='-'||s=='+') {
int signe=(s=='+')?1:-1;
n=signe*lecture_entier_sans_signe(ch+1);
}
else n=lecture_entier_sans_signe(ch);
cout<<"merci pour "<<n<<endl;
}
main() {
int n;
lecture_entier(n);
} |
Partager