在IP格式判断方面的函数问题求助
查看原帖
在IP格式判断方面的函数问题求助
836643
Asher12楼主2023/9/30 18:27

allalpha函数是我用来判断是否是a.b.c.d:e格式的函数,对数字范围没有判断功能。

在如下程序中,我编写了一个测试程序,包含allalpha函数,给出的IP地址是1.1.1.1:1,符合题目中的IP格式,但bool变量输出为0。

#include <iostream>
#include <string>
using namespace std;
bool allalpha(string str)
{
	int id=0;
	int cnt=0;
	while (str.find(".",id)==string::npos)
	{
		cnt++;
		id=str.find(".",id);
	}
	if (cnt!=3)
	{
		return false;
	}
	id=0;
	cnt=0;
	while (str.find(":",id)==string::npos)
	{
		cnt++;
		id=str.find(":",id);
	}
	if (cnt!=1)
	{
		return false;
	}
	int dotscnt=0,coloncnt=0;
	for (int i=0;i<str.size();i++)
	{
		if (str[i]=='.')
		{
			dotscnt++;
			if (coloncnt!=0)
			{
				return false;
			}
		}
		else if (str[i]==':')
		{
			coloncnt++;
			if (dotscnt!=3)
			{
				return false;
			}
		}
	}
	return true;
}
int main()
{
	string str="1.1.1.1:1";
	cout<<allalpha(str);
	return 0;
}

请问allalpha函数中出现了哪些问题?


注:编译环境为MicrosoftTM Windows 7 Unimate Service Pack 1,intel CORETM i7,22.2GB硬盘,Dev\tiny\mathcal{注:编译环境为Microsoft^{TM}\ Windows\ 7\ Unimate\ Service\ Pack\ 1,intel\ CORE^{TM}\ i7,22.2GB硬盘,Dev}-C\tiny\mathcal{C}++ 5.11,TDM\tiny\mathcal{\ 5.11,TDM}-GCC 10.3.0\tiny\mathcal{GCC\ 10.3.0}

2023/9/30 18:27
加载中...