diff --git a/stream_management.cpp b/stream_management.cpp new file mode 100644 index 0000000..c7486ba --- /dev/null +++ b/stream_management.cpp @@ -0,0 +1,40 @@ +#include +#include +using std::string, std::cout, std::cin; + +class Student +{ + int age{}; + string info{}; + +public: + friend std::istream &operator>>(std::istream &is, Student &s) + { + // 先输入年龄,再输入信息 + while (true) + { + cout << "请输入学生的年龄(20-60):"; + is >> s.age; + if (is && s.age >= 20 && s.age <= 60) + break; + is.clear(0); + is.ignore(std::numeric_limits::max(), '\n'); + } + is.ignore(std::numeric_limits::max(), '\n'); // 清除之前遗漏的多余字符和回车 + while (true) + { + cout << "请输入学生的信息(至少10字节):"; + getline(is, s.info); // getline默认以回车为终止标记,且会提走并丢弃回车符 + if (s.info.length() >= 10) // 这里的10涉及编码细节,不展开讨论 + break; + } + return is; + } +}; + +int main() +{ + Student s{}; + cin >> s; + return 0; +} \ No newline at end of file