Reputation:
I am trying to get 4 integers from an IP-address. For example, 12.34.56.78. A = 12, b = 34, c = 56, and d = 78. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ADDRESS[100];
printf("Enter IP: ");
scanf("%s", ADDRESS);
return 0;
}
How would I be able to do this?
Upvotes: 0
Views: 662
Reputation: 147
if you're asked to read it as a string at first , you need to add a condition that it exists 4 points in the string
do {
count=0;
for (i=0;i<strlen(address);i++) {
if (address[i] == '.')
count++;
}
if (count > 4) {
printf("Enter IP: ");
scanf("%s", ADDRESS); }
while (!(count <= 4));
secondly using strtok can make everything easy , you have to split your string with the .
caracter so it goes with something like this
char *tester;
int counter=0,a,b,c,d;
tester = strtok(address, ".");
while( tester != NULL ) {
switch (counter) {
case 0:
a=atoi(tester);
counter++;
break;
case 1:
b=atoi(tester);
counter++;
break;
case 2 :
c=atoi(tester);
counter++;
break;
case 3:
d=atoi(tester);
counter++;
break; }
tester= strtok(NULL, ".");
}
Upvotes: 0
Reputation: 14107
try to use good old sscanf()
.
int A, B, C, D;
sscanf(ADDRESS, "%d.%d.%d.%d", &A, &B, &C, &D);
It may be a good idea to check if sscanf()
returned 4 what indicates that all four numbers were correctly parsed.
Upvotes: 5