前言
众所周知,getline经常用来读取一行的字符串。
但真的是这样吗?
getline的实现
getline实现(basic_string.h):
/**
* @brief Read a line from stream into a string.
* @param __is Input stream.
* @param __str Buffer to store into.
* @param __delim Character marking end of line.
* @return Reference to the input stream.
*
* Stores characters from @a __is into @a __str until @a __delim is
* found, the end of the stream is encountered, or str.max_size()
* is reached. Any previous contents of @a __str are erased. If
* @a __delim is encountered, it is extracted but not stored into
* @a __str.
*/
template<typename _CharT, typename _Traits, typename _Alloc>
basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim);
/**
* @brief Read a line from stream into a string.
* @param __is Input stream.
* @param __str Buffer to store into.
* @return Reference to the input stream.
*
* Stores characters from is into @a __str until '\n' is
* found, the end of the stream is encountered, or str.max_size()
* is reached. Any previous contents of @a __str are erased. If
* end of line is encountered, it is extracted but not stored into
* @a __str.
*/
template<typename _CharT, typename _Traits, typename _Alloc>
inline basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Alloc>& __str)
{ return std::getline(__is, __str, __is.widen('\n')); }
#if __cplusplus >= 201103L
/// Read a line from an rvalue stream into a string.
template<typename _CharT, typename _Traits, typename _Alloc>
inline basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>&& __is,
basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim)
{ return std::getline(__is, __str, __delim); }
/// Read a line from an rvalue stream into a string.
template<typename _CharT, typename _Traits, typename _Alloc>
inline basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>&& __is,
basic_string<_CharT, _Traits, _Alloc>& __str)
{ return std::getline(__is, __str); }
#endif
template<>
basic_istream<char>&
getline(basic_istream<char>& __in, basic_string<char>& __str,
char __delim);
#ifdef _GLIBCXX_USE_WCHAR_T
template<>
basic_istream<wchar_t>&
getline(basic_istream<wchar_t>& __in, basic_string<wchar_t>& __str,
wchar_t __delim);
#endif 我们发现getline的参数是:
__in:输入使用的变量(cin也是个istream类的变量),只能填cin或wcin。__str:要输入的字符串。__delim:读入到什么字符结束(默认为\n)
我们便可以写出以下代码:
string s;
getline(cin, s, ' '); //这其实就是cin >> s又因为__in是istream类型,getline也是istream类型,所以我们便可以写出以下奇怪的代码:
string s1, s2;
getline(getline(cin, s1), s2); //getline嵌套
int x;
getline(cin >> x, s1); //getline套cin
cin >> s1 >> getline(cin, s2); //直接输入
//当然也可以无限嵌套甚至:
getline(cin, s1) >> s2; //getline当cin
while (getline(cin, s1)){} //while (cin)语法
//注意要开c++17或者搭配stringstream:
stringstream ss("input a line");
getline(ss, s1);都可以(不会报错)。