gpt4 book ai didi

c - 从由 ' . ' 分隔的字符串中添加数字

转载 作者:行者123 更新时间:2023-12-04 18:13:24 26 4
gpt4 key购买 nike

我想编写一个 C 程序,它将从用户那里获取一个 IP 地址,如字符串中的 "112.234.456.789",并在字符串中的每个 block 之外提供格式化输出,例如,上述 IP 地址的 "04.09.15.24"。这是我到目前为止所拥有的:

#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();
}

输入应该是类似 "112.234.546.234" 的 IP 地址,输出应该是在每个 block 中添加数字的结果 "04.09.15.06" 。输入和输出应该是字符串。

最佳答案

您的代码的问题是 s[c]!='.'||s[c]!='\0'将对输入中的任何字符评估为真——甚至是 '.' .这意味着 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com