Converting a Text into an Integer RRS feed

  • Question

  • Hi,

    I'm in need of a conversion routine to convert a string into a integer(long). I'm relying on CRT function _tcstol to do this. Below shown is my approach:

    _TCHAR *q = 0;
    char txt[] = "5x";
    long l = _tcstol(txt, &q, 10);
    if (q && _tcsclen(q))
    cout<<"Invalid Integer";

    I'm relying on parameter2 in _tcstol to validate a integer. (i.e)the endptr Pointer to character that stops scan.

    Will this approach work fine in all cases?

    Thanks in Advance

    Saturday, August 30, 2008 9:28 AM


  • Well, for starters, your code is not "Unicode-correct". It should be

    TCHAR *q = 0;
    TCHAR txt[] = _T("5x");
    long l = _tcstol(txt, &q, 10);

    Note that _TCHAR and TCHAR are the same. I always use the latter.

    Otherwise, your approach should work, I think.

    David Wilkinson | Visual C++ MVP
    • Marked as answer by Yan-Fei Wei Tuesday, September 2, 2008 8:18 AM
    Saturday, August 30, 2008 11:46 AM