| CODE |
| ////////////////// //char to double// //by Dr Voodoo // ////////////////// #include <iostream> using namespace std; //The first argument is the char array to be converted //The second is a pointer to a bool. If an error ocures //this bool will contain true is no error ocures it will //be false. double char_to_double(char*str,bool*error) { *error=true; double out=0; int pos=0; for(int i=strlen(str)-1;i>=0;i--) { switch (str[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { double val=(double)(str[i]-'0'); for(int i=0;i<pos;i++) val*=10; pos++; out+=val; } break; case ',': case '.': { for(int i=0;i<pos;i++) out/=10; pos=0; } break; case '-': { if(i!=0) return 0; out*=-1; } break; default: return 0; } } *error=false; return out; } main () { while(1==1) { cout<<"Enter a number or enter q to exit:"<<endl; char char_num[64]; cin>>char_num; if(char_num[0]=='q') return 0; cout<<"Converting char array to double"<<endl; bool error; double double_num=char_to_double(char_num,&error); if(error) { cout<<"Error during convertion!"<<endl<<endl; } else { cout<<"Here is your number this time as double: "<<double_num<<endl<<endl; } } return 0; } |
| CODE |
float value; if (sscanf(myString,"%f",&value) == 1) { // There was a number and 'value' is now valid. } else { // The string does not contain a number at the start. } |