c - 将由 ' . ' 分隔的字符串中的数字相加

标签 c string

我想编写一个 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/

相关文章:

c - 打印存储在 char 数组中的\x 转义字符

c++ - 为什么与 C 相比,链接器在 C++ 中的任务更艰巨?

c - 向链表中插入一个字符串

java - 正则表达式 - 使用正则表达式在另一个字符串中搜索特定字符串

在 C 中将 time_t 转换为给定格式的字符串

python - 检查两个项目是否在列表中但不在固定顺序中?

c - 如何使用C\C++中的while循环(system.ping)来ping渐进式IP

c - Dijkstra 算法 : Why is it needed to find minimum-distance element in the queue

c - 定义一个包含数据数组和一些指向相同数据数组区域的指针的结构

java - 添加空字符串与 toString - 为什么不好?