蓝桥杯 IP判断

题目

题目大意:判断IP地址中的四部分数字是否满足0~255;

解题思路:首先需要获得每个部分的字符串,然后把字符串转换为数字(当然,此处需要判断是否为数字,也可能是字母),判断该数字是否在0~255之间。

获取用‘.’分开的字符串可以使用重载符号“+”

s += str[i];

关键是如何将字符串转换为数字呢?此处有个简单的方法;

#include <sstream>//所需头文件
	
stringstream ss(s);
int num;
ss >> num;

以上代码是将字符串s转换为数字num,stringstream就相当于是中间介质。

源码附上:

(源代码参考http://www.dotcpp.com/blog/3247-4.html)

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

bool judge(string str)
{
	int i = 0;
	while (i < str.length())
	{
		string s;
		while (str[i] != '.'&&i < str.length())
		{
			if (str[i] >= '0'&&str[i] <= '9')
			{
				s += str[i];
				i++;
			}
			else
			{
				return false;
			}
		}
		i++;
		stringstream ss(s);
		int num;
		ss >> num;
		if (num < 0 || num>255)
			return false;
	}
	return true;
}

int main()
{
	string s;
	while (cin >> s)
	{
		int temp = judge(s);
		if (temp)
			cout << "Y" << endl;
		else
			cout << "N" << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Exaggeration08/article/details/86568674