C++中cin.get 和cin.peek 及其相关的用法

今天写代码遇到了 一点点困惑,题目要求大体为:html

  输入一串数字(包含一些空格)当键入回车时计算出输入数字的和ios

其实现代码以下:数组

 1 #include<iostream>
 2 using namespace std;  3 
 4 int main()  5 {  6      int a;  7      int sum;  8      
 9      while(cin>>a) 10  { 11          sum+=a; 12          while(cin.peek()==' ')//观测到当前字符为空格的话 13  { 14              cin.get();    //从流中提取当前的空格 15  } 16          
17          if(cin.peek()=='\n')  //观测到当前字符为换行符的话直接终止 18          break; 19  } 20      
21      cout<<"结果是:"<<sum<<endl; 22      return 0; 23     
24  }

 

程序里用到了cin.peek()和cin.get(),顺便学习一下这两个的用法:函数

参考博文传送门:http://c.biancheng.net/cpp/biancheng/view/2231.html学习

        https://blog.csdn.net/ReCclay/article/details/60782267测试

下面是我对于这两个函数用法的一个简单输出测试:spa

 1 #include<iostream>
 2 using namespace std;  3 
 4 int main()  5 {  6     int a;  7     int b;  8     int c;  9     while(cin>>a) 10  { 11         b+=a; 12         while(cin.peek()==' ') //探测到空格 
13  { 14             c=cin.get(); //这里是提取出空格 
15             cout<<"a="<<a<<endl ; 16  } 17         if(cin.peek()=='\n') 18  { 19             break; 20  } 21         
22  } 23     cout<<"和为:"<<b<<endl; 24     cout<<"c = "<<c<<endl; 25 }

测试输入输出结果为:【输入为1 2 3 4 5】.net

  

【输入为12 13 14 2 3】指针

 

  这里c实际上是提取出的空格的ASCII码,因此是32,而至于a则是每次提取提取出的数字。code

 cin.get()

  函数是cin输入流对象的成员函数,它有3种形式:无参数的,有一个参数的,有3个参数的。

  无参数的相似于C语言中的getchar(),从制定的输入流中提取一个字符。C语言中的getchar函数与流成员函数cin.get( )的功能相同,C++保留了C的这种用法,能够用getchar(c)从键盘读入一个字符赋给c。

  无参数用来从指定的输入流中提取一个字符(包括空白字符),函数的返回值就是读入的字符。 若遇到输入流中的文件结束符,则函数值返回文件结束标志EOF(End Of File),通常以-1表明EOF,用-1而不用0或正值,是考虑到不与字符的ASCII代码混淆,但不一样的C ++系统所用的EOF值有可能不一样。

有一个参数:

      cin.get(ch)
   其做用是从输入流中读取一个字符,赋给字符变量ch。若是读取成功则函数返回true(真),如失败(遇文件结束符) 则函数返回false(假)。

有两个参数:

      cin.get(字符数组, 字符个数n, 终止字符)
  或
      cin.get(字符指针, 字符个数n, 终止字符)
  其做用是从输入流中读取n-1个字符,赋给指定的字符数组(或字符指针指向的数组),若是在读取n-1个字符以前遇到指定的终止字符,则提早结束读取。若是读取成功则函数返回true(真),如失败(遇文件结束符) 则函数返回false(假)。

传送门:http://c.biancheng.net/cpp/biancheng/view/2231.html

    https://blog.csdn.net/ReCclay/article/details/60782267

cin.peek()

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

 1 #include <iostream>
 2 using namespace std;  3 int main ()  4 {  5     char c;  6     int n;  7     char str[256];  8     cout << "Enter a number or a word: ";  9     c=cin.peek(); 10     if ( (c >= '0') && (c <= '9') ) 11  { 12         cin >> n; 13         cout << "You have entered number " << n << endl; 14  } 15     else
16  { 17         cin >> str; 18         cout << " You have entered word " << str << endl; 19  } 20     return 0; 21 }
相关文章
相关标签/搜索