3

I have a string that contains a 14-digit number.

I want to convert the string to an int.

When I use atoi(stringName), I get the max 32-bit in limitation.

Example:

String1 contains "201400000000"

long long tempNum1;
tempNum1 = atoi(String1);
printf("%d",tempNum1);

Output is: 2147483647

How can I turn this string into a number? I want to compare it to other strings of numbers and find which is the largest. (I have three strings of 14-digit numbers, I want to find which is the smallest, which is the largest).

plc
  • 33
  • 5
  • I have to wonder what you were expecting `tempNum1 = sprintf(String1,NULL,10);` to do. – user253751 Oct 08 '15 at 08:01
  • As could be guess from it's name [`atoi`](http://en.cppreference.com/w/c/string/byte/atoi) only deals with `int`. You might want to use [`strtoll`](http://en.cppreference.com/w/c/string/byte/strtol) instead. – Some programmer dude Oct 08 '15 at 08:02
  • 1
    it should be printf("%llu",tempNum1); and use strtoI for string to long conversion – user2979190 Oct 08 '15 at 08:10
  • `long` is still 32 bits on Windows and most 32-bit *nix OSes. Only `long long` is guaranteed to have at least 64 bits – phuclv Oct 08 '15 at 08:16
  • Thanks all. strtoll works. Also thanks @user2979190 for mentioning the format specifier! – plc Oct 08 '15 at 08:26

4 Answers4

3

atoi returns an int.

That int is assigned to a long long, but by then the limit has already been reached.

You want to use atoll which returns a long long.

And your printf format specifier is incorrect for your type.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
3

Since your target is a long long int, you can use the strtoll function:

#include <stdlib.h>

long long tempNum1 = strtoll(String1, NULL, 10);
melpomene
  • 81,915
  • 7
  • 76
  • 137
1

You can try like this using strol:

long strtol (const char *Str, char **EndPoint, int Base)

or

long long strtoll( const char *restrict str, char **restrict str_end, int base );

The atoi says:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
1

try

 sscanf( String1, "%lld", &TempNum1);

Note that the format specifier %lld works for C99 , if not C99 please check the docs for the compiler

Jibin Mathew
  • 3,232
  • 1
  • 25
  • 42