////////////////////////////////////////
// 2008-08-08
// Stone
// Implements the first occurrence of a valid number in a string
// Extract it, for example, abge _ + * 123.456 dfsdf
// The running result should be: 123.456
///////////////////////////////////////
# Include <iostream>
# Include <cstring>
# Include <cstdio>
# Define maxlen 50 // defines the previous character array
Using namespace STD;
Int main ()
{
Char numstr [maxlen];
Int flag = 1, I = 0, j = 0, H = 0;
Double m = 0, sum = 0, n = 0;
Cout <"enter a string :";
Cin> numstr;
// 1. Remove +-or 0 ~ 9 contains invalid characters;
For (; I <strlen (numstr); I ++)
{
If (numstr [I] <= '9' & numstr [I]> = '0 ') | numstr [I] = '+' | numstr [I] = '-')
Break;
Else
J ++;
}
If (numstr [J] = '-') // judge the negative number to prepare for the final output.
Flag =-1;
If (numstr [J] = '+' | numstr [J] = '-') // Point J to the first numeric element (excluding the +-sign)
J ++;
I = J; // Let I also point to the first numeric Element
// 2. Remove invalid characters after the number element;
H = J;
For (; I <strlen (numstr); I ++)
{
If (numstr [I] <= '9' & numstr [I]> = '0') | numstr [I] = '.')
H ++;
Else
Break;
}
H-= 1;
// 3. Calculate the integer part
/*
If (numstr [J] = '-')
{
Flag =-1;
J ++;
}
If (numstr [J] = '+ ')
J ++;
*/
For (; numstr [J]! = '.' & J <= H; j ++) // integer part calculation implementation
{
N = N * 10 + numstr [J]-'0 ';
}
// 4. Calculate the fractional part
If (j <H & numstr [H]! = '.')
{
For (J ++; j <= H; h --) // Let J point to the first numeric character and calculate from the last element
{// Decimal part until H = J is stopped.
M = m * 0.1 + numstr [H]-'0 ';
}
M * = 0.1;
}
// 5. Merge digits
Sum = N + m;
Sum = sum * flag;
Cout <"output conversion character Result :";
Cout <sum <Endl;
Printf ("printf output result: % lf", sum );
Return 0;
}