Reputation: 89
I'm having trouble with this...It compiles, but segfaults immediately when run...Using GDB, I determined that it segfaults while trying to initiate the long doubles. I feel like atoi might be the wrong function to use, but I tried other similar functions and still got a segfault.
int main(int argc, char *argv[]) {
long double x = atoi(argv[1]);
char oper = argv[2][0];
long double y = atoi(argv[3]);
Upvotes: 0
Views: 146
Reputation: 225042
atoi()
stands for "ascii to integer", which isn't what you want. You should use an appropriate function — strtold(3)
is most appropriate, but you can probably use sscanf(3)
, too.
Upvotes: 4
Reputation: 477368
Use strtold
:
#include <stdlib.h>
#include <errno.h>
char * e;
errno = 0;
long double d = strtold(argv[1], &e);
if (*e != 0 || errno != 0) { /* Error! Do not consume the result. */ }
// result now in "d"
You can use the value of *e
to figure out whether any part of the string was consumed; see the manual for details. My example just checks whether the entire string could be parsed.
I'm actually not sure if there's a thread-safe solution... (Oh, I think it is, because errno
is thread-local.)
Upvotes: 2
Reputation: 183968
The correct way to convert a string to a long double
is
long double strtold(const char *nptr, char **endptr);
Upvotes: 2