Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All..

Am facing problem in extracting only numbers from CString. Am having a string like
Example 1: CString cs = "1697.7 ST 8.2 BIIU__LL 1697.60 1698.30 "
Example 2: CString cs1 = "16588 ST 78 BJ89__LL 1685.90 1623.87 "

And i want to extract only numbers from this string.Output like :
1697.7 8.2 1697.60 1698.30

How to achieve this, please suggest/guide me..


Thank you all.
Posted

1 solution

You must write your own parser to do this. Assuming that the elements are separated by spaces and all numbers are floating point numbers, this can be done using strtod():
C++
// Get space separated floating point number as CString object.
// Empty string if not a floating point value.
// Returns pointer to next space, trailing NULL char, or NULL
LPCTSTR GetNumberStr(CString& str, LPCTSTR s) const
{
    while (*s <= _T(' '))
        ++s;
    LPTSTR lpszEnd;
    _tcstod(s, &lpszEnd);
    // Floating point or int value if conversion stopped at space or end of string
    if (*lpszEnd <= _T(' '))
        str.SetString(s, static_cast<int>(lpszEnd - s));
    else
    {
        str = _T("");
        // This may return NULL!
        lpszEnd = _tcschr(s, _T(' '));
    }
    return lpszEnd;
}

void Parse(CString& strOut, const CString& strIn) const
{
    strOut = _T("");
    LPCTSTR s = strIn.GetString();
    while (s && *s)
    {
        CString str;
        s = GetNumberStr(str, s);
        if (!str.IsEmpty())
        {
            if (!strOut.IsEmpty())
                strOut += _T(' ');
            strOut += str;
        }
    }
}
 
Share this answer
 
Comments
Guru_C++ 12-Dec-12 4:55am    
Thanks for replying... But am getting this error: error C2440: '=' : cannot convert from 'const char *' to 'LPTSTR' on this line
lpszEnd = _tcschr(s, _T(' '));
Guru_C++ 12-Dec-12 5:04am    
I tried type casting like this..
lpszEnd =(TCHAR*) _tcschr(s, _T(' '));

It worked fine.. And am getting exact output..

Thank you..
Jochen Arndt 12-Dec-12 5:09am    
I just wanted to answer that casting would do it (I compiled the code with an older VS version that does not show this error).
Alternatively, just return here: 'return _tcschr(s, _T(' '));'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900