-1

I'm trying to convert this string "09195462965" to an int but I'm running into problems.

snippet of my code:

int n, p, pnum=0;
char buffer[256];
char *endptr;
long pnumber;

bzero(buffer,256);
p = read(sock,buffer,255);

    pnumber = strtol(buffer, &endptr, pnum);

printf("n: %ld",pnumber);

p = write(sock,buffer,sizeof(buffer));

A client sends a string of "09195462965" then the server receives it.

Now on the server that string must be turned into an int i.e. 09195462965.

Note: the server sends the number as string.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user1553142
  • 237
  • 1
  • 11
  • 21

2 Answers2

3

You're using strtol() incorrectly, the last parameter should be the base that you want. For example if you want to store that number in base 10 (decimal):

long pnumber;
pnumber = strtol("09195462965", NULL, 10); //nst char *nptr is "09195462965"
                                           //char **endptr  is null
                                           //int base       is 10 for decimal
printf("n: %ld",pnumber);

>> 9195462965

Make sure you read the man page for the function you're using.

Passing pnum (which is set to 0) as your doing for the last parameter is causing it to spit back "0", because of the number you're passing in.

09195462965 has digits from 0-9 (so I assume you wanted dec) if you pass in "0" to strtol() then it's going to see that first 0 and will treat the number has octal, the problem with that is that octal numbers go from 0-7, thus the 9's are "out of bounds" for an octal number and as such strtol() spits back 0.

with a number like: 07175462765, you'd be fine to pass in pnum when it's 0.

Mike
  • 47,263
  • 29
  • 113
  • 177
  • 1
    *If the value of base is zero, the expected form of the subject sequence is that of an integer constant as described in [...]* So `base = 0` might be what the op is after, if the number is to be interpreted as octal. I only added the quote because you posted in your answer ***make sure you read the man page...*** ;) – cnicutar Nov 25 '12 at 16:00
  • @cnicutar - oh no worries there, I just didn't both to explain *why* that string was invalid with `pnum=0`, as I assumed OP would read the man page and figure it out. ;) But I updated it now. – Mike Nov 25 '12 at 16:38
1

That's too big to fit in an int. Try strtoumax and store it in an uintmax_t.

uintmax_t pnumber = strtoumax(buffer, &endptr, 10);
if (pnumber == UINTMAX_MAX && errno == ERANGE)
    /* Too big. */

Alternatively, if you don't have strtoumax you can try strtoull et al.

cnicutar
  • 178,505
  • 25
  • 365
  • 392