peek()函数------本文章转载自他处

C++中的peek函数

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

  其功能是从输入流中读取一个字符 但该字符并未从输入流中删除  若把输入流比作一个 栈类 那么这里的peek函数就相当于栈的成员函数front 而如果cin.get()则相当于栈的成员函数pop。

  下面这段代码能帮助您更清晰地理解peek函数

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


 

C中的peek函数(自己写的)

[cpp] view plain copy
 
  1. char peek_char;  
  2.   
  3. static char peek()  
  4. {  
  5.     return peek_char;  
  6. }  
  7.   
  8. static void * __Peek_loop_func(void *pInputArg)  
  9. {  
  10.     char tmp_char;  
  11.     while(1)  
  12.     {  
  13.         if(tmp_char=getchar())  
  14.         {             
  15.             if((tmp_char!='\r')&&(tmp_char!='\n')&&(tmp_char!=0x0a))  
  16.             {  
  17.                 peek_char=tmp_char;  
  18.                 printf("Input Char === [%c] \n",peek_char);   
  19.   
  20.                 if(peek_char=='q')  
  21.                 {  
  22.                     printf("Jmp out from serial == 2 \n");  
  23.                     exit(1);  
  24.                 }  
  25.             }  
  26.         }  
  27.         usleep(1000*10);  
  28.     }  
  29. }  
  30.   
  31. // 下面的代码放在主程序中,用来创建检测输入的线程.  
  32.   
  33. pthread_t tPeekThreadHandle;  
  34. pthread_create(&tPeekThreadHandle, NULL, &__Peek_loop_func, NULL);  


原理就是创建一个新线程,来接收串口的输入,如果输入的第一字符为‘q’ 则退出程序,其实在退出的时候,我们也可以再捕获一下。

posted @ 2017-04-21 20:35  极地啸天  阅读(618)  评论(0编辑  收藏  举报