Cpp-standard-library-cpp-basic-ios-peek

提供:Dev Guides
移動先:案内検索

C ++ basic_iosライブラリ-ピーク

説明

次の文字を覗くために使用されます。

宣言

以下は、std
basic_istream :: peekの宣言です。
int_type peek();

パラメーター

none

戻り値

入力シーケンスの次の文字を、抽出せずに返します。文字は、ストリームから抽出される次の文字として残されます。

例外

基本保証-例外がスローされた場合、オブジェクトは有効な状態です。

データの競合

ストリームオブジェクトを変更します。

以下のstd
basic_istream :: peekの例。
#include <iostream>
#include <string>
#include <cctype>

int main () {

   std::cout << "Please, enter a number or a word: ";
   std::cout.flush();

   std::cin >> std::ws;
   std::istream::int_type c;
   c = std::cin.peek();

   if ( c == std::char_traits<char>::eof() )
   return 1;
   if ( std::isdigit(c) ) {
      int n;
      std::cin >> n;
      std::cout << "You entered the number: " << n << '\n';
   } else {
      std::string str;
      std::cin >> str;
      std::cout << "You entered the word: " << str << '\n';
   }

   return 0;
}

出力は次のようになります-

Please, enter a number or a word: foobar
You entered the word: foobar