Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top