问题 1116: IP判断
时间限制: 1Sec 内存限制: 128MB 提交: 5123 解决: 2048
题目描述
在基于Internet的程序中,我们常常需要判断一个IP字符串的合法性。
合法的IP是这样的形式:
A.B.C.D
其中A、B、C、D均为位于[0, 255]中的整数。为了简单起见,我们规定这四个整数中不允许有前导零存在,如001这种情况。
现在,请你来完成这个判断程序吧_
输入
输入由多行组成,每行是一个字符串,输入由“End of file”结束。
字符串长度最大为30,且不含空格和不可见字符
输出
对于每一个输入,单独输出一行
如果该字符串是合法的IP,输出Y,否则,输出N
样例输入
1.2.3.4
a.b.c.d
267.43.64.12
12.34.56.bb
210.43.64.129
-123.4.5.6
样例输出
Y
N
N
N
Y
N
这道题真的踩坑无数 string 遇到空格不会读入,想读入空格必须用getline(cin,str),上面说以End of file结束,我以为是以字符串“End of file” 结束,还死活AC不了,瞬间被自己蠢哭。。。。。
#include
#include
#include
using namespace std;
int main()
{
string end="End of file";
string str;
string temp;
while(getline(cin,str))
{
bool flag=true;
int position=1;
for(string::iterator it=str.begin();it!=str.end();it++)
{
if(*it>='0'&&*it<='9'||*it=='.')
{
if(position==1&&*it=='0')
{
flag=false;
break;
}
if(*it!='.')
{
temp.push_back(*it);
position=0;
}
if(*it=='.'||it+1==str.end())
{
int ans=0;
for(string::iterator temp_it=temp.begin();temp_it!=temp.end();temp_it++)
{
ans=ans*10+*temp_it-'0';
}
temp.clear();
if(ans<0||ans>255)
{
flag=false;
break;
}
position=1;
}
}
else
{
flag=false;
break;
}
}
if(flag== true)
{
cout<<"Y"<<endl;
} else
{
cout<<"N"<<endl;
}
}
return 0;
}