int _tmain(int argc, _TCHAR* argv[])
{
char str[80];
int oct[4];
int i;
printf("Enter your IP address:");
scanf ("%s",str);
int * pch;
pch = strtok (str,".");
for(i=0;i<5;i++)
{
printf ("%s\n",pch);
oct[i]= (pch&);
pch = strtok (NULL,".");
}
system("PAUSE");
return 0;
}
How would I get this to work? I have been playing with C++, have a program working, and I need a way to break up an IP address and store each octet in an array of integers. Maybe one of you elite programmers can help a n00b. Thanks.
Name:
Anonymous2006-04-09 3:19
instead of oct[i] = (pch&), you need to have a loop that iterates over each digit character, convert it to a numeric digit, multiply by the appropriate place value (1 for the first digit, 10 for the second digit, 100 for the third digit), and add it to oct[i]. At the end of the loop oct[i] should have the correct value.
I think the following works, but I'm not sure:
int place = pow(10, strlen(pch) - 1);
oct[i] = 0;
for (int j = 0; pch[j] != 0; j++) {
oct[i] += (pch[j] - '0') * place;
place /= 10;
}
Name:
Anonymous2006-04-09 4:42
>>1
is this supposed to be C++? looks like plain old C to me. oh well, whatever.
just include the stdlib header, and replace "oct[i]= (pch&);" with "oct[i]= atoi(pch);", that'll convert a string into an integer for you.
while you're at it, pch should be a pointer to char, not int. and you've got an off-by-one error in your loop.
i'd also throw in a quick integrity check on the number before parsing it. nothing to stop someone from just keying 192.168.5 as an ip address and segfaulting the program.
Name:
Anonymous2006-04-09 4:49
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char s[64];
int b[4];
char *p;
int i;
/* get the IP */
printf("Enter your IP address: ");
fgets(s, 64, stdin);
/* scan it */
p = strtok(s, ".");
for (i = 0; i < 4; i++) {
sscanf(p, "%d", &b[i]);
p = strtok(NULL, ".");
}
/* and print it back to check */
printf("IP: %d.%d.%d.%d\n", b[0], b[1], b[2], b[3]);
return 0;
}
Name:
Anonymous2006-04-09 4:50
>>4
after the sscanf, add: if (b[i] > 255) b[i] = 0;
Name:
Anonymous2006-04-09 11:38
>>4
Wow, thanks alot. I will post the program source and compiled version sometime. I will be sure to credit anonymous reply number 4. Thanks :)