当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ basic_istream::peek()用法及代码示例


std::basic_istream::peek()用于从输入流中读取下一个字符而不提取它。该函数不接受任何参数,仅返回输入字符串中的下一个字符。以下是相同的语法:

头文件:

#include<iostream>

用法:

int peek();

返回值:std::basic_istream::peek()返回输入字符串中的下一个字符。

下面的程序可以更好地了解std::basic_istream::peek()的实现:



程序1:

// C++ code for std::basic_istream::peek() 
#include <bits/stdc++.h> 
using namespace std; 
  
// main method 
int main() 
{ 
    istringstream gfg("GeeksforGeeks"); 
  
    char c1 = gfg.peek(); 
    char c2 = gfg.get(); 
    char c3 = gfg.get(); 
  
    cout << "The first character is:"
         << c1 << endl 
         << " and the next is:"
         << c3 << endl; 
}
输出:
The first character is:G 
and the next is:e

程序2:

// C++ code for std::basic_istream::peek() 
#include <bits/stdc++.h> 
using namespace std; 
  
// main method 
int main() 
{ 
    istringstream gfg("Computer"); 
  
    char c1 = gfg.peek(); 
    char c2 = gfg.get(); 
    char c3 = gfg.get(); 
  
    cout << "The first character is:"
         << c1 << endl 
         << " and the next is:"
         << c3 << endl; 
}
输出:
The first character is:C 
and the next is:o

程序3:

// C++ code for std::basic_istream::peek() 
#include <bits/stdc++.h> 
using namespace std; 
  
// main method 
int main() 
{ 
    istringstream gfg("Laptop"); 
  
    char c1 = gfg.peek(); 
    char c2 = gfg.get(); 
    char c3 = gfg.get(); 
    char c4 = gfg.get(); 
  
    cout << "The first character is:"
         << c1 << endl 
         << " and the next is:"
         << c3 << endl 
         << " after that next is:"
         << c4 << endl; 
}
输出:
The first character is:L 
and the next is:a 
after that next is:p

参考:http://www.cplusplus.com/reference/istream/basic_istream/peek/




相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 basic_istream::peek() in C++ with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。