當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。