一、题目描述
火星人是以 13 进制计数的:
【PAT乙级刷题/1044 火星数字/C++实现】例如地球人的数字29翻译成火星文就是hel mar;而火星文elo nov对应地球数字115 。为了方便交流,请你编写程序实现地球和火星数字之间的互译 。
输入格式:
输入第一行给出一个正整数N( 输出格式:
对应输入的每一行 , 在一行中输出翻译后的另一种语言的数字 。
输入样例:
4295elo novtam//结尾无空行
输出样例:
hel marmay11513//结尾无空行
二、思路分析
1. () 的用法
#include #include #include int main(){// greet the userstd::string name;std::cout << "What is your name? ";std::getline(std::cin, name);std::cout << "Hello " << name << ", nice to meet you.\n";// read file line by linestd::istringstream input;input.str("1\n2\n3\n4\n5\n6\n7\n");int sum = 0;for (std::string line; std::getline(input, line); ) {sum += std::stoi(line);}std::cout << "\nThe sum is: " << sum << "\n\n";// use separator to read parts of the linestd::istringstream input2;input2.str("a;b;c;d");for (std::string line; std::getline(input2, line, ';'); ) {std::cout << line << '\n';}}
What is your name? John Q. PublicHello John Q. Public, nice to meet you.The sum is 28abcd
2.cin和()一起使用的注意事项
C++中()和cin同时使用时的注意事项
3.stoi的用法
#include #include int main(){std::string str1 = "45";std::string str2 = "3.14159";std::string str3 = "31337 with words";std::string str4 = "words and 2";int myint1 = std::stoi(str1);int myint2 = std::stoi(str2);int myint3 = std::stoi(str3);// error: 'std::invalid_argument'// int myint4 = std::stoi(str4);std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';}
std::stoi("45") is 45std::stoi("3.14159") is 3std::stoi("31337 with words") is 31337
三、题解代码以及提交截图
#include #include using namespace std;const string low_digit[13] = {"tret", "jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};const string high_digit[13] = {"#", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};void MarToEarth(const string& s){int t1 = 0, t2 = 0,len = s.length();string s1 = s.substr(0, 3), s2;if (len > 4) s2 = s.substr(4, 3);for (int j = 1; j <= 12; j++) {if (s1 == low_digit[j] || s2 == low_digit[j]) t2 = j;if (s1 == high_digit[j]) t1 = j;}cout << t1 * 13 + t2;}void EarthToMar(const int& t){if (t / 13) cout << high_digit[t / 13];if ((t / 13) && (t % 13)) cout << " ";if (t % 13 || t == 0) cout << low_digit[t % 13];}int main(){int N;string s;cin >> N;getchar();for (int i = 0; i < N; i++) {getline(cin, s);if (s[0] >= '0' && s[0] <= '9')EarthToMar(stoi(s));elseMarToEarth(s);cout << endl;}return 0;}