Convert MFC CString to integer

后端 未结 11 2056
南旧
南旧 2020-12-08 13:15

How to convert a CString object to integer in MFC.

相关标签:
11条回答
  • 2020-12-08 13:52

    If you are using TCHAR.H routine (implicitly, or explicitly), be sure you use _ttoi() function, so that it compiles for both Unicode and ANSI compilations.

    More details: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

    0 讨论(0)
  • 2020-12-08 13:52

    The problem with the accepted answer is that it cannot signal failure. There's strtol (STRing TO Long) which can. It's part of a larger family: wcstol (Wide Character String TO Long, e.g. Unicode), strtoull (TO Unsigned Long Long, 64bits+), wcstoull, strtof (TO Float) and wcstof.

    0 讨论(0)
  • 2020-12-08 13:52

    Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

    int atoi(
       const char *str 
    );
    int _wtoi(
       const wchar_t *str 
    );
    int _atoi_l(
       const char *str,
       _locale_t locale
    );
    int _wtoi_l(
       const wchar_t *str,
       _locale_t locale
    );
    

    CString is wchar_t string. So, if you want convert Cstring to int, you can use:

     CString s;  
    int test = _wtoi(s)
    
    0 讨论(0)
  • 2020-12-08 13:54

    i've written a function that extract numbers from string:

    int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
       // get startIndex
       int startIndex = src.Find(str) + CString(str).GetLength();
       // cut the string
       CString toreturn = src.Mid(startIndex, length);
       // convert to number
       return _wtoi(toreturn); // atoi(toreturn)
    }
    

    Usage:

    CString str = _T("digit:1, number:102");
    int  digit = GetNumberFromCString(str, _T("digit:"), 1);
    int number = GetNumberFromCString(str, _T("number:"), 3);
    
    0 讨论(0)
  • 2020-12-08 14:03
    CString s;
    int i;
    i = _wtoi(s); // if you use wide charater formats
    i = _atoi(s); // otherwise
    
    0 讨论(0)
  • 2020-12-08 14:04
    CString s="143";
    int x=atoi(s);
    

    or

    CString s=_T("143");
    int x=_toti(s);
    

    atoi will work, if you want to convert CString to int.

    0 讨论(0)
提交回复
热议问题