[英]How can I get 4 integers from an IP address string?
I am trying to get 4 integers from an IP-address.我正在尝试从 IP 地址中获取 4 个整数。 For example, 12.34.56.78.
例如,12.34.56.78。 A = 12, b = 34, c = 56, and d = 78. Here is my code:
A = 12,b = 34,c = 56,d = 78。这是我的代码:
#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?我怎么能做到这一点?
try to use good old sscanf()
.尝试使用好的旧
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.检查
sscanf()
是否返回 4 表示所有四个数字都已正确解析可能是个好主意。
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如果一开始要求您将其读取为字符串,则需要添加一个条件,即它在字符串中存在 4 个点
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 .
其次,使用strtok可以让一切变得简单,你必须用
.
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, ".");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.