一个可消除输入的\r\n对字符串的影响的函数,嗯…其实我也不知道有啥用
最近在巩固基础知识,帮一个大一童靴解决了个小问题,他们老师的这种用法之前未见过,应该是我孤陋寡闻了,在此记录一下,方便回顾、学习。
好吧,看代码。
```cpp
#include <iostream>
#include <string>
using namespace std;
void mygetline(std::istream& input, string& p)
{
char ch1;
ch1 = cin.peek();
while (ch1 == '\n' || ch1 == '\r')
{
cin.get();
ch1 = cin.peek();
}
std::getline(input, p);
if(p[p.length()-1] == '\r')
{
p[p.length()-1] = 0;
p.resize(p.size()-1);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string strScore;
cout << "测试mygetline(),可消除\\r\\n对字符串的影响。\n" ;
mygetline(cin, strScore);
for (int i = 0; i < (int)strScore.size(); i++)
{
cout << strScore[i];
}
cout << endl;
}
**basic_istream::peek**
功能: Returns the next character to be read.
返回值:The next character that will be read.
例如:MSDN示例代码:
int main( )
{
char c[10], c2;
cout << "Type 'abcde': ";
c2 = cin.peek( );
cin.getline( &c[0], 9 );
cout << c2 << " " << c << endl;
}
Input: abced
Output: a abced
**basic_istream::get**
功能:Reads one or more characters from the input stream.