Reputation: 883
I am new to C++ and am having an issue converting a signed char to a double. Initial idea was to convert the signed char to a const char* and use atof to return the double.
signed char x = '100';
const char * cChar = x;
std::cout << atof(cChar);
What can I try to resolve this?
Upvotes: 0
Views: 2440
Reputation: 100602
It should just be:
double value = static_cast<double>(x);
What you're currently doing is creating a pointer to memory address 100, which you almost certainly don't own, then attempting to read a string from there, which almost certainly isn't there.
(note: I originally suggested the C-style version, double value = (double)x;
, see the comments below as to why C-style casts are better avoided in C++)
Upvotes: 0
Reputation: 1942
I'm trying to get my head around what your current understanding is
signed char x = '100';
This line of code is taking the character '100' which doesn't exist, typically characters are one symbol long such as 'a' and '9'. Unless they are special non printable sequences such as null '\0' or newline '\n', or even escaped characters such as single quote'\''
C style string are represented by double quotations and have one hidden byte at the end that hold a null terminator, the double quote notation deals with the null for you.
if your looking to convert the string "100" to a double then the following will work
double a;
char b [4] = "100";
a = atof(b);
Upvotes: 0
Reputation: 5177
You might want to use strtod()
or you can use boost::lexical_cast<>
Upvotes: 1
Reputation: 91260
signed char x = 100;
double d = x;
cout << d;
const char * x = "100";
double d = atof(x);
cout << d;
'100'
is wrong - you need either a const char * x = "100";
or a char x=100
;
Upvotes: 2