坐标移动
题目描述
开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
输入:
合法坐标为A(或者D或者W或者S) + 数字(两位以内)
坐标之间以;分隔。
非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。
下面是一个简单的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
处理过程:
起点(0,0)
+ A10 = (-10,0)
+ S20 = (-10,-20)
+ W10 = (-10,-10)
+ D30 = (20,-10)
+ x = 无效
+ A1A = 无效
+ B10A11 = 无效
+ 一个空 不影响
+ A10 = (10,-10)
结果 (10, -10)
输入描述:
一行字符串
输出描述:
最终坐标,以,分隔
输入例子:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
输出例子:
10,-10
解答代码:
#include<iostream>
#include<fstream>
#include<string>
#include<algorithm>
#include<sstream>
#include<string>
#include<cstring>
using namespace std;
double convertFromString(const string &s)
{
istringstream i(s);
double x;
if(i>>x)
return x;
return 0.0;
}
int judge(string s)
{
int i,count=0;
//每一步操作不超过3个字符:A100无效
if(s.length()>3)
return 0;
//空格是无效字符
for(i=0; i<s.length(); i++)
if(s[i]==' ')
count++;
if(count==s.length())
{
count=0;
return 0;
}
//s串为空
if(s.length()==0)
return 0;
//ASWD每一步只出现一次:B10A11无效 或者 其他非法字符: x非法
for(i=0; i<s.length(); i++)
{
if(s[i]!='A'&&s[i]!='S'&&s[i]!='W'&&s[i]!='D'&&!(s[i]>='0'&&s[i]<='9'))
return 0;//非法字符出现
if(s[i]=='A'||s[i]=='S'||s[i]=='W'||s[i]=='D')
count++;
}
if(count>=2||count==0)//操作字符多于2个或者没有操作字符
return 0;
return 1;
}
int main()
{
string s;
char ss[10000];
int i,length;
int x=0,y=0;
//ifstream fin("input.txt");
while(cin.getline(ss,9999))
{
x=0,y=0;
length=strlen(ss);
s="";
for(i=0; i<length; i++)
{
if(ss[i]!=';')
s=s+ss[i];
else
{
if(judge(s))
{
//cout<<s<<endl;
//处理:分离操作符和操作数
char ch=s[0];
string temp="";
int data;
for(int i=1; i<s.length(); i++)
temp=temp+s[i];
data=convertFromString(temp);
//cout<<ch<<"+"<<data<<endl;
if(ch=='A')
x-=data;
else if(ch=='D')
x+=data;
else if(ch=='W')
y+=data;
else if(ch=='S')
y-=data;
}
s="";
}
}
cout<<x<<','<<y<<endl;
}
//fin.close();
return 0;
}