我想编写一个 C 程序,它将从用户那里获取 IP 地址,如字符串中的 "112.234.456.789"
,并除了字符串中的每个 block 之外还提供格式化输出,例如 “04.09.15.24”
为上述 IP 地址。这是我到目前为止所拥有的:
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s[15],d[11];
int i=0,c = 0, sum[4] = {0};
d[i]=sum[c]/10;
printf("Enter ip address:");
gets(s);
printf("\n \n %s",s);
i=0;
for(c=0;c<15;c++)
{
if(s[c]!='.'||s[c]!='\0')
sum[i]=(s[c]-48)+sum[i];
else
i++;
}
for(i=0,c=0;c<4;c++,i+=3)
{
d[i]=(sum[c]/10)+48;
d[i+1]=sum[c]%10+48;
d[i+2]='.';
}
printf("\n \n %s",d);
getch();
}
输入应该是一个IP地址,如“112.234.546.234”
,输出应该是每个 block 中的数字相加的结果,“04.09.15.06”
>。输入和输出应该是字符串。
最佳答案
您的代码的问题是 s[c]!='.'||s[c]!='\0'
将对输入中的任何字符求值为 true - 甚至 '.'
。这意味着i
永远不会增加,只是每个数字相加为 sum[0]
,但 '.' - 48
也是如此.
你的意思是s[c] != '.' && s[c] != '\0'
.
我写了你想要的函数here .
#include <stdio.h>
#include <ctype.h>
void convert(const char *in, char *out) {
unsigned int sum = 0;
char ch;
do {
ch = *in++;
if (isdigit(ch)) {
sum += ch - '0';
} else {
*out++ = sum / 10 + '0';
*out++ = sum % 10 + '0';
if (ch == '.') {
*out++ = '.';
sum = 0;
}
}
} while (ch);
}
顺便说一下,each "block" of the IPv4 address is an octet ,而您正在做的是将每个替换为 digit sum .
关于c - 将由 ' . ' 分隔的字符串中的数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167572/