注册 登录
编程论坛 VC++/MFC

字符串分割和连接出现一个诡异的问题无法解决

jidipiaoyu 发布于 2011-08-30 11:09, 454 次点击
char* IP   =   "192.168.1.24";
char* IP1=strstr(IP,".")+1;
char *p1 = strtok(IP, ".");
char* IP2=strstr(IP1,".")+1;
char *p2 = strtok(IP1, ".");
char *p3 = strtok(IP2, ".");
char* ipend=p1;
ipend=strcat(ipend,".");
ipend=strcat(ipend,p2);
ipend=strcat(ipend,".");
ipend=strcat(ipend,p3);
ipend=strcat(ipend,".");
ipend=strcat(ipend,"255");
运行到最后ipend的值为192..1.255,p2的值莫名其妙就变成空了,请高手指教下。
3 回复
#2
hahayezhe2011-08-30 11:23
我明白了 你是想将"192.168.1.24";改为192.168.1.255吧

我的天 那用这么麻烦哦 strtok会破坏参数1的完整性的

从后面往前找
或者直接转化为16进制后再改
    char p[] = "192.168.1.23";
    char ipsend[20] = {0};
    char *p1 = p;
    p1 = p1+(_tcslen(p));

    for(;p1!=p;p1--){
        if(*p1 == '.'){
            memcpy(ipsend,p,p1-p);
            ipsend[p1-p] = '.';
            _tcscat(ipsend,"255");
            break;
        }
    }

    printf("%s\n",ipsend);
#3
hahayezhe2011-08-30 11:35
char p[] = "192.168.1.23";
    in_addr i;
    i.S_un.S_addr = inet_addr(p);
    i.S_un.S_un_b.s_b4 = 255;
#4
jidipiaoyu2011-08-30 11:52
回复 3楼 hahayezhe
多谢大侠,两个方法都可以用,谢谢啦!
1