其他与输入的istream类成员函数

1.eof函数

表示文件结束

#include <iostream>
using namespace std;
int main( )
{
   char c;
   while(!cin.eof( ))  //eof( )为假表示未遇到文件结束符
   if((c=cin.get( ))!=' ')  //检查读入的字符是否为空格字符
      cout.put(c);
   return 0;
}

C++ is very interesting.↙
C++isveryinteresting.
^Z(结束)

peek函数

cin.peek();

函数的返回值是指针指向的当前字符,但它只是观测,指针仍停留在当前位置,并不后移。如果要访问的字符是文件结束符,则函数值是EOF(-1)。

putback函数

cin.putback(ch);

其作用是将前面用get或getline函数从输入流中读取的字符ch返回到输入流,插入到当前指针位置,以供后面读取。

 1 #include <iostream>
 2 using namespace std;
 3 int main( )
 4 {
 5    char c[20];
 6    int ch;
 7    cout<<"please enter a sentence:"<<endl;
 8    cin.getline(c,15,'/');
 9    cout<<"The first part is:"<<c<<endl;
10    ch=cin.peek( );  //观看当前字符
11    cout<<"The next character(ASCII code) is:"<<ch<<endl;
12    cin.putback(c[0]);  //将'I'插入到指针所指处
13    cin.getline(c,15,'/');
14    cout<<"The second part is:"<<c<<endl;
15    return 0;
16 }

please enter a sentence:
I am a boy./ am a student./↙
The first part is:I am a boy.
The next character(ASCII code) is:32(下一个字符是空格)
The second part is:I am a student

ignore函数

cin.ignore(n,终止字符)

cin.ignore()相当于ignore(I,EOF)

可以利用cin.ignore()跳过'\',上一篇,里面,因为cin.getline()会把指针停在'\',造成下一个cin.getline()不能读取。

猜你喜欢

转载自www.cnblogs.com/Mayfly-nymph/p/8995841.html
今日推荐