[编程题]坐标移动

Talk is cheap, show me the code.

一、问题描述

开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

输入:

合法坐标为A(或者D或者W或者S) + 数字(两位以内)

坐标之间以;分隔。

非法坐标点需要进行丢弃。如AA10; A1A; <script type="math/tex" id="MathJax-Element-1">%</script>; 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

二、问题分析

首先这个字符串是以分号分隔的,以何种方式去读取每个分号分隔出的字符串有几种方式,最好的方式是采用getline设置以分号为分隔读入一个字符串。也可以用逐个找到分号的方式来读入每个字符串。

解题方式1:

以getline(流,存储字符串,分隔符)来设置以分号为分隔符读入每个字符串的方式。

#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;

int main()
{
    string str;
    while (cin >> str)
    {
        istringstream is(str);
        string s;
        int x = 0, y = 0;
        while (getline(is, s, ';'))
        {
            if (s.size() == 3 && isalpha(s[0]) && isdigit(s[1]) && isdigit(s[2]) || (s.size() == 2 && isalpha(s[0]) && isdigit(s[1])))
            {
                int num = atoi(s.substr(1).c_str());
                switch(s[0])
                {
                    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;
}

解题方式2:

以找分号的方式读入每个字符串。

include

include

include

using namespace std;

int main()
{
string str;
while (cin >> str)
{
int x = 0, y = 0;
string::size_type end = str.find_first_of(‘;’);
while (end != string::npos)
{
string s = str.substr(0, end);
if (end == str.size())
break;
str = str.substr(end + 1);
end = str.find_first_of(‘;’);
if (s.size() == 3 && isalpha(s[0]) && isdigit(s[1]) && isdigit(s[2]) || (s.size() == 2 && isalpha(s[0]) && isdigit(s[1])))
{
int num = atoi(s.substr(1).c_str());
switch(s[0])
{
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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值