長記性:英語數字轉換器

題目鏈接

我吐了

getline完了以後記得判斷字符串是否爲空,數據可能會給空行

#include <iostream>
#include <cstring>
#include <string>
#include <unordered_map>
#include <sstream>
using namespace std;
using LL = long long;

unordered_map<string, int> h;

void in(){
    h["zero"] = 0;
    h["one"] = 1;
    h["two"] = 2;
    h["three"] = 3;
    h["four"] = 4;
    h["five"] = 5;
    h["six"] = 6;
    h["seven"] = 7;
    h["eight"] = 8;
    h["nine"] = 9;
    h["ten"] = 10;
    h["eleven"] = 11;
    h["twelve"] = 12;
    h["thirteen"] = 13;
    h["fourteen"] = 14;
    h["fifteen"] = 15;
    h["sixteen"] = 16;
    h["seventeen"] = 17;
    h["eighteen"] = 18;
    h["nineteen"] = 19;
    h["twenty"] = 20;
    h["thirty"] = 30;
    h["forty"] = 40;
    h["fifty"] = 50;
    h["sixty"] = 60;
    h["seventy"] = 70;
    h["eighty"] = 80;
    h["ninety"] = 90;
}

int main()
{
    in();
    string s;
    while(getline(cin, s)){
        if(s.empty()) break; // 這句必須加上,否則報錯!
        bool neg = 0;
        LL ans = 0;
        istringstream is(s);
        string t;
        int n = 0;
        while(is >> t){
            if(t == "negative") neg = 1;
            else if(t == "million") n *= 1000000, ans += n, n = 0;
            else if(t == "thousand") n *= 1000, ans += n, n = 0;
            else if(t == "hundred") n *= 100;
            else n += h[t];
        }
        ans += n;
        if(neg) ans = -ans;
        cout << ans << endl;
    }
    system("pause");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章