- Steve - wrote:
I have an array of char values that I need to assign to a integer variable.
I tried casting it: integer = (int)charArray; but when I run it I get
incorrect results in integer. What is the correct way to cast a string to
an integer?
Avoid casts whenever possible. Avoid C-style casts always. This is a
good example of why: the code you tried to use does nothing even
remotely similar to what you want, but the cast prevents the compiler
from warning you of that fact. Had you used a C++ cast operator instead,
you would have found that you needed reinterpret_cast, and that would
have (or should have) served as a warning that it wasn't doing what you
wanted.
Next piece of advice: Don't use char pointers and arrays for strings.
Use std::string. It's much easier to deal with and much less
error-prone. Here's an example of what (I think) you want to do:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string str("4922");
std::istringstream strin(str);
int i;
strin >> i;
std::cout << str << " = " << i << std::endl;
return 0;
}
Think of 'strin' as 'cin' but using the string supplied to it as its
data source, rather than the program's standard input.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.