peek()函数------本文章转载自他处
C++中的peek函数
该调用形式为cin.peek() 其返回值是一个char型的字符,其返回值是指针指向的当前字符,但它只是观测,指针仍停留在当前位置,并不后移。如果要访问的字符是文件结束符,则函数值是EOF(-1)。
其功能是从输入流中读取一个字符 但该字符并未从输入流中删除 若把输入流比作一个 栈类 那么这里的peek函数就相当于栈的成员函数front 而如果cin.get()则相当于栈的成员函数pop。
下面这段代码能帮助您更清晰地理解peek函数
- /* istream peek */
- #include <iostream>
- using namespace std;
- int main ()
- {
- char c;
- int n;
- char str[256];
- cout << "Enter a number or a word: ";
- c=cin.peek();
- if ( (c >= '0') && (c <= '9') )
- {
- cin >> n;
- cout << "You have entered number " << n << endl;
- }
- else
- {
- cin >> str;
- cout << " You have entered word " << str << endl;
- }
- return 0;
- }
C中的peek函数(自己写的)
- char peek_char;
- static char peek()
- {
- return peek_char;
- }
- static void * __Peek_loop_func(void *pInputArg)
- {
- char tmp_char;
- while(1)
- {
- if(tmp_char=getchar())
- {
- if((tmp_char!='\r')&&(tmp_char!='\n')&&(tmp_char!=0x0a))
- {
- peek_char=tmp_char;
- printf("Input Char === [%c] \n",peek_char);
- if(peek_char=='q')
- {
- printf("Jmp out from serial == 2 \n");
- exit(1);
- }
- }
- }
- usleep(1000*10);
- }
- }
- // 下面的代码放在主程序中,用来创建检测输入的线程.
- pthread_t tPeekThreadHandle;
- pthread_create(&tPeekThreadHandle, NULL, &__Peek_loop_func, NULL);
原理就是创建一个新线程,来接收串口的输入,如果输入的第一字符为‘q’ 则退出程序,其实在退出的时候,我们也可以再捕获一下。