Add stream_management.cpp

main
p68710245 1 year ago
parent f12ab52e3a
commit 3bf95787d0

@ -0,0 +1,40 @@
#include <iostream>
#include <string>
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<std::streamsize>::max(), '\n');
}
is.ignore(std::numeric_limits<std::streamsize>::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;
}
Loading…
Cancel
Save