注意混合输入时要去掉换行符,否则,输入n后缓冲区残余的'\n'会被getline读入造成错误
// #include <iostream> // #include <vector> // #include <algorithm> // #include <string> // using namespace std; // // 自定义排序函数:按字符串长度排序 // bool compareByLength(const string &a, const string &b) { // return a.size() < b.size(); // } // int main() { // int n; // while (cin >> n) { // 每次循环读取n,直到EOF // cin.ignore(); // 清除输入缓冲区中的换行符 // vector<string> strings; // 存储字符串的动态容器 // for (int i = 0; i < n; ++i) { // string str; // getline(cin, str); // 读取一行字符串 // if (str == "stop") { // break; // 如果遇到 "stop",提前结束输入 // } // else { // strings.push_back(str); // 将字符串添加到容器 // } // } // // 按长度排序字符串 // sort(strings.begin(), strings.end(), compareByLength); // // 输出排序后的字符串 // for (const auto &str : strings) { // cout << str << endl; // } // } // return 0; // } #include <iostream> #include <map> #include <string> using namespace std; int main() { int n; string s; map<int, string> count; while (cin >> n) { cin.ignore(); // 忽略n后面的换行符 for (int i = 0; i < n; i++) { getline(cin, s); int size = s.size(); if (s == "stop") { break; } count[size] = s; } // 输出结果 for (auto it = count.begin(); it != count.end(); it++) { cout << it->second << endl; } count.clear(); // 为下一组数据做准别 } return 0; }