坐标移动
开发一个坐标计算工具, 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)
#include <bits/stdc++.h>
#include <ctype.h>
#include <string>
using namespace std;
bool isA_S(char c) {
if (c == 'A'||c == 'D'||c == 'S' || c == 'W')
return true;
else return false;
}
int main() {
string str;
while(getline(cin, str)){
stringstream input(str);
vector<string> data;
string temp;
int x = 0, y = 0;
while (getline(input, temp, ';')) {
if (temp.length() == 3 && isA_S(temp[0]) && isdigit(temp[1]) && isdigit(temp[2])) {
data.push_back(temp);
}
else if (temp.length() == 2 && isA_S(temp[0]) && isdigit(temp[1])) {
data.push_back(temp);
}
}
for (int i = 0; i < data.size(); i++) {
char first = data[i][0];
int num = 0;
if (data[i].size() == 3) {
num = stoi(data[i].substr(1, 2));
}
else if (data[i].size() == 2) {
num = stoi(data[i].substr(1, 1));
}
switch (first) {
case 'A':x -= num; break;
case 'D':x += num; break;
case 'W':y += num; break;
case 'S':y -= num; break;
}
}
cout<<x<<','<<y<<endl;
}
return 0;
}