1

I am writing a code in which I need to parse a string to a "long long int"

I used to use atoi when changing from string to int, I dont think it still work. What Can I use now?

--Thanks

Syntax_Error
  • 5,964
  • 15
  • 53
  • 73
  • 2
    The phrase you're looking for is "parse a string as a (long long) integer". Leave "change" to the politicians :-) – Kerrek SB Feb 02 '12 at 19:42

1 Answers1

7

Use strtoll() (man page):

#include <stdlib.h>

long long int n = strtoll(s, NULL, 0);

(This is only available in C99 and C11, not in C89.) The third argument is the number base for the conversion, and 0 means "automatic", i.e. decimal, octal or hexadecimal are selected depending on the usual conventions (10, 010, 0x10). Just be mindful of that in case your string starts with 0.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 100% correct, but two warnings: First, the automatic base can be confusing, because 010 is 8 (obvious to some, absurd for others). Second, it doesn't really do error checking. So "7up" becomes 7, and "hello" becomes 0. – ugoren Feb 02 '12 at 19:54