解题思路:把字符串用.隔开,判断是否为数字,不是返回false;如果是运用atoi函数转为int并判断是大于0小于255,是返回true。
注意事项:巧妙地运用了atoi函数
参考代码:
#include<iostream>
#include<string>
#include<cstdlib>//atoi头文件
using namespace std;
bool judge(string str)
{
string str1;
int i=0;
while(i<str.length())
{
while(str[i]!='.'&&i<str.length())
{
if(str[i]>='0'&&str[i]<='9')
{
str1+=str[i];
}
else
{
return false;
}
i++;
}
int num;
num=atoi(str1.c_str());//string 转num
if(num<0||num>255)
{
return false;
}
str1="";//把string清空
i++;//越过.
}
return true;
}
int main()
{
string str;
while(cin>>str)
if(judge(str)==true)
cout<<"Y"<<endl;
else
cout<<'N'<<endl;
}
0.0分
0 人评分