1. C++中string类的练习,使用的数据结构慢慢地开始有心得了;
2. string类中的+=操作符和append( )函数的使用;
3. 这道题很简单,开始出错是因为string类型的变量没有初始化。string str = "";//初始化为空字符串;
4. 推荐一个c++的网站(cplusplus.com - The C++ Resources Network)。
#include <iostream> #include <string> #include <cstring> using namespace std; struct type { string str; char let; int len; }ltr[30]={{".-",'A',2},{"-...",'B',4},{"-.-.",'C',4},{"-..",'D',3},{".",'E',1},{"..-.",'F',4},{"--.",'G',3},{"....",'H',4},{"..",'I',2},{".---",'J',4},{"-.-",'K',3},{".-..",'L',4},{"--",'M',2},{"-.",'N',2},{"---",'O',3},{".--.",'P',4},{"--.-",'Q',4},{".-.",'R',3},{"...",'S',3},{"-",'T',1},{"..-",'U',3},{"...-",'V',4},{".--",'W',3},{"-..-",'X',4},{"-.--",'Y',4},{"--..",'Z',4},{"..--",'_',4},{".-.-",',',4},{"---.",'.',4},{"----",'?',4}}; int main() { string str_in, tmp, str_out, tmp_m; int num[101], i, k, mm, nn, cas, j; cin >> cas; for (i = 1; i <= cas; i++) { str_in = ""; cin >> str_in; memset(num, 0, sizeof(num)); str_out = ""; tmp = ""; for (j = 0; j < str_in.length(); j++) for (k = 0; k < 30; k++) if (str_in[j] == ltr[k].let) { tmp += ltr[k].str; num[j] = ltr[k].len; break; } // cout << tmp << endl; // for (j = 0; j < str_in.length(); j++) // cout << num[j]; // cout << endl; mm = num[str_in.length() - 1]; nn = 0; for (j = str_in.length() - 1; j >= 0; j--) { tmp_m = ""; for (k = nn; k < mm; k++) tmp_m += tmp[k]; // cout << tmp_m << endl; for (k = 0; k < 30; k++) if (tmp_m == ltr[k].str) { str_out += ltr[k].let; break; } nn += num[j]; mm += num[j-1]; } cout << i << ": " << str_out << endl; } return 0; }