题解 | #坐标移动# 有点啰嗦,但是也运行成功了
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream> #include <sstream> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; // bool isValidCoord(char dir, int num) { // // 检查方向是否合法 // if (dir != 'A' && dir != 'W' && dir != 'S' && dir != 'D') // return false; // // 检查数字是否合法 // if (num <= 0 || num > 99) // return false; // return true; // } //检查坐标是否有效 bool isValidCoord(const string& coord) { //判断字符长度有效 if (coord.size() < 2 || coord.size() > 3) return false; char dir = coord[0]; int len = coord.size(); // 检查第一个字符是否合法方向 if (dir != 'A' && dir != 'W' && dir != 'S' && dir != 'D') return false; //判断字符串后边是不是数字 for (int i = 1; i < len; i++) { if (!isdigit(coord[i])) return false; } return true; } //处理坐标字符串, 返回最终坐标 Point processCoordinates(const string& input) { stringstream ss(input); string line; Point point = {0, 0}; while (getline(ss, line, ';')) { stringstream lineStream(line); char dir; int num; if(isValidCoord(line)){ while (lineStream >> dir >>num) { string coordinate = string(1, dir) + to_string(num); if (isValidCoord(coordinate)) { switch (dir) { case 'A': point.x -= num; break; case 'D': point.x += num; break; case 'W': point.y += num; break; case 'S': point.y -= num; break; } } else { cout << "Coordinate is invalid." << endl; } } } } return point; } int main() { string input; getline(cin, input); Point result = processCoordinates(input); cout << result.x << ',' << result.y << endl; return 0; }