Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

練習 文字列等

文字列等の練習にコマンドと引数の対をとるコードを書いてみた。引数には対自体を入れることができるとする。

結果はこんな感じになる。

>+ * 100
(+ (* ( 100)))
#ifndef RDCalc_hpp
#define RDCalc_hpp

#include <stdio.h>
#include "RDConfig.hpp"

class Command {
public:
    Command() = default;
    ~Command() = default;
    
    std::string name;
    std::string description();
};


class Value;

class Term {
public:
    Term() = default;
    ~Term() = default;
    std::shared_ptr<Command> command;
    std::shared_ptr<Term> value;
    std::string name;
    std::string description();
};

class Value : public Term {
public:
    Value();
    ~Value() = default;
};




class RDCalc {
public:
    RDCalc();
    ~RDCalc();
    void start();
    std::string calc(std::string);
    std::shared_ptr<Term> state;
private:
    std::shared_ptr<Term> getTerm(std::vector<std::string>);
    
};

#endif /* RDCalc_hpp */
//
//  RDCalc.cpp
//  RDCalcSystem
//
//  Created by KatagiriSo on 2017/09/26.
//  Copyright © 2017年 RodhosSoft. All rights reserved.
//

#include <sstream>
#include <iostream>
#include "RDCalc.hpp"
#include<string>
#include<vector>

RDCalc::RDCalc() {
    
}

RDCalc::~RDCalc() {
    std::cout << "RDCalc dec.\n";

}

void RDCalc::start() {
    std::string input;

    while(true) {
        std::cout << ">";
        
        std::string str;
        std::vector<std::string> v;

        std::getline(std::cin, str);
        
        auto output = RDCalc::calc(str);
        std::cout << output << std::endl;
    }
}

std::vector<std::string> splitString(std::string input) {
    std::stringstream ss;
    ss << input;
    
    std::vector<std::string> v;
    
    std::string com;
    while(ss >> com) {
        v.push_back(com);
    }
    return v;
}




std::string RDCalc::calc(std::string input) {
    
    std::vector<std::string> v = splitString(input);
    
    this->state = getTerm(v);
    
    if (this->state == nullptr) {
        return "?\n";
    }
    
    return this->state->description();
}

std::shared_ptr<Term> RDCalc::getTerm(std::vector<std::string> v) {
    
    auto term = std::make_shared<Term>();
    auto command = std::make_shared<Command>();
    
//    if (m=="+") {
//
    auto m = v.front();
    v.erase(v.begin());
    if (v.empty()) {
        term->command = command;
        term->command->name = "";
        auto value = std::make_shared<Value>();
        value->name = m;
        term->value = value;
    } else {
        command->name = m;
        
        term->command = command;
        term->value = getTerm(v);
    }
    
    
    return term;
}


std::string Term::description() {
    if (this->value == nullptr) {
        return this->name;
    }
    return "(" + this->command->description() + " " + this->value->description() + ")";
}

std::string Command::description() {
    return this->name;
}

Value::Value() {
    command = std::make_shared<Command>();
    command->name = "";
}