You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
951 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
#include <string>
using std::string, std::cout, std::cin;
class Student
{
char info[11];
int age{};
public:
friend std::istream &operator>>(std::istream &is, Student &s)
{
// 改为先输入信息,再输入年龄
cout << "请输入学生的信息(最多10字节)";
is.getline(s.info, 10);
if (!is)
{
is.clear();
clearerr(stdin);
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
while (true)
{
cout << "请输入学生的年龄(20-60)";
is >> s.age;
if (is && s.age >= 20 && s.age <= 60)
break;
is.clear(0);
clearerr(stdin); // 遇到ctrl+z或ctrl+d等情况下clear并不能直接修复流需要使用clearerr
}
return is;
}
};
int main()
{
Student s{};
cin >> s;
return 0;
}