//简单模拟,重点掌握string cin cout #include <iostream> #include <string> using namespace std; string calc(string str) { int i, j = 0; int num[10] = {0}; char inv[81]; for(i = 0; i < str.length(); i++) //c++ ! { num[str[i]-'0']++; } for(i = 0; i < 10; i++) { if (num[i] > 0 && num[i] < 10) { inv[j++] = num[i] + '0'; inv[j++] = i + '0'; // i + 48 } else if (num[i] >= 10) { inv[j++] = num[i] / 10 + '0'; inv[j++] = num[i] % 10 + '0'; inv[j++] = i + '0'; } } inv[j] = '/0'; return inv; } void funSolve(string str) { int i, j; bool ok = false; //c++! string inv[16]; //??? string temp = str; // c++! 相当于c中的strcpy(temp, str),方便不少。 for(i = 0; i < 15; i++) { temp = calc(temp); for(j = 0; j < i; j ++) { if(temp == inv[j]) { ok = true; break; } } if(ok) { if(i == 1 && j == 0) { cout << str << " is self-inventorying" << endl; return; //用的很好!从当前函数跳转到调用该函数的任何地方.此时跳出函数。 } else if(j == i - 1) { cout << str << " is self-inventorying after " << i << " steps/n"; return; } else { cout << str << " enters an inventory loop of length " << i - j << endl; return; } } inv[i] = temp; } cout << str << " can not be classified after 15 iterations/n"; } int main() { char str[100]; while (1 == scanf("%s", str)) { // cin >> str; if(str[0] == '-') break; funSolve(str); } return 0; } c++入门经典 第六章。