[ale] OT: c++ datatypes question
Fulton Green
ale at FultonGreen.com
Mon Jun 7 15:14:27 EDT 2004
On Mon, Jun 07, 2004 at 03:01:07PM -0400, J.M. Taylor wrote:
> Palm has a datatype WORD which is an unsigned, 16-bit int. I am trying to
> read in a delimited record from a text file into a buffer and assign
> what's in the buffer as the value of the variable in question (let's call
> it wVar). I cannot change the datatype of wVar. So, ignoring the mechanics
> of reading in the value, which works just fine, let's say the buffer I
> read into is called tmp.
>
> wVar = (unsigned short) atoi(tmp); (or, (unsigned __int16) atoi(tmp))
> compiles just fine but dies at runtime.
Since you're using C++, have you tried using the C++-style streaming
operators? For example,
#include <sstream>
// ...
std::istringstream iss(tmp, std::istringstream::in);
tmp >> wVar;
The atoi() function, as well as countless other C-style standard functions,
are considered "legacy" when used in a modern C++ (i.e., has a robust
Standard Template Library (STL)) development context.
> sprintf((char*)wVar,"%u",tmp);
> Compiles and doesn't crash at runtime, but I'm getting a zero value which
> isn't right. Setting the value staticly, like sprintf((char*)wVar,"2")
> gives me a zero value too.
This does the exact opposite of what you need. You'd want to try sscanf()
instead, but remember that these functions, like atoi(), are considered
"legacy" in a modern C++ context.
More information about the Ale
mailing list