tags:

views:

282

answers:

7

I'm trying to convert an LPCSTR to an integer using atoi(), and to verify that the conversion occurred successfully I want to count the number of digits in the integer it produced and the original LPCSTR (it should contain nothing but integers)

I'm having a hard time finding a good way to calculate the length of the LPCSTR. So far the only way seems to be just counting until I get to a '/0'

Any suggestions for a better method?

Thanks

+2  A: 

Nope.

That's how you find the length of a c-string. You could use strlen, but it still has to go down the whole string and count the number of characters before a '\0'.

Eclipse
+7  A: 

Isn't that what strlen does?

sean riley
Doh! Sorry guys, brain fart. Must have had some kind of a mental block to not remember this one and never see it on any of my searches
Zain
+7  A: 

You could use strtol and use the endptr returned to check if it's the end of the string (0 byte).

Counting will not necessarily be accurate. "00" will result in 0, but 0 has one digit and the original string has length 2.

Rüdiger Hanke
+2  A: 

The strlen() function is what you're looking for.

Sample usage:

size_t len = strlen( szNumber );
Matt Dillard
+2  A: 

Talk about producing more heat than light... :) Stop using 'atoi' and that will solve most of your problems. 'atoi' is a dead function with no practical value. The proper way to convert a string representation to a number is functions from 'strto...' group ('strtol', 'strtoul' etc.). These functions will return enough information back to you to determine right away whether a conversion error occured or not.

AndreyT
A: 

I'd do things a bit differently -- initialize a stringstream with the input, read an int, then check whether the stream is empty:

#include <sstream>
#include <iostream>

typedef char const *LPCSTR;

template <class T>
bool check_read(LPCSTR input, T &val) { 
    std::istringstream reader(input);

    reader >> val;
    char ch;
    if (reader >> ch) {
        std::cerr << "\nUnconverted character: " << ch << std::endl;
        return false;
    }
    return true;
}

int main() { 
    LPCSTR inputs[] = {"12345", "54321a"};
    int a;

    for (int i=0; i<2; i++) {
        check_read(inputs[i], a);
        std::cout << "Converted: " << a << std::endl;
    }
    return 0;
}

Another reasonable possibility would be strtol or one of its cousins. These return a pointer to the first un-converted character (if any), so they tell you fairly directly what was and wasn't converted. They're faster but generally less flexible than streams -- for example, if you want to read a floating point number, the check_read above will work as-is, but something using strtol would need to be rewritten.

As yet one more possibility, you might consider Boost lexical_cast (which is packaged a little differently, but pretty similar to the code above).

Jerry Coffin
A: 
LPCSTR lpText = "test";
long lTextLen = CString(lpText).GetLength();
armadillo