我有以下一段 C++ 代码:
string dots="...";
char *points=(char *)malloc(sizeof(char)*20);
strcpy(points,dots.c_str());
points=strtok(points,".");
while(points!=NULL)
{
cout<<points<<endl;
points=strtok(NULL,".");
}
cout 语句不打印任何内容。cout 为 0 长度标记匹配返回的这个字符是什么?我试图检查 '\0' 但不起作用。请帮忙。
编辑:验证 IP 地址的完整程序
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
int validateIP(string);
int main()
{
string IP;
cin>>IP;
int result=validateIP(IP);
if(result==0)
cout<<"Invalid IP"<<endl;
if(result==1)
cout<<"Valid IP"<<endl;
return 0;
}
//function definition validateIP(string)
int validateIP(string IP)
{
char ip[16];
int dotCount=0;
strcpy(ip,IP.c_str());
//check number of dots
for(int i=0;i<strlen(ip);++i)
{
if(ip[i]=='.')
{
dotCount++;
}
}
if(dotCount!=3)
return 0;
//check range
char *numToken;
numToken = strtok (ip,".");
while (numToken!= NULL)
{
int number;
if(numToken!=NULL) //check for token of length 0(e.g. case: ...)
number=atoi(numToken); //i also checked for (numToken[0]!='\O')
else return 0;
if(number<0 or number>255)
return 0;
numToken=strtok (NULL,".");
}
return 1;
}
程序打印 ValidIP 以供输入: ...