Number extraction in a string (C ++)

Source: Internet
Author: User

 

////////////////////////////////////////
// 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;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.