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.
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
{
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 ) ;
clearerr ( stdin ) ; // 遇到ctrl+z或ctrl+d等情况下, clear并不能直接修复流, 需要使用clearerr
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 ;
}