C++ istream::peek() 函数



C++ 的 std::istream::peek() 函数用于检查输入流中的下一个字符,但不提取它。它允许预览即将到来的字符,同时将其保留在流中以备将来使用。它将下一个字符作为 int 或 EOF(如果到达流的末尾)返回。

与 get() 不同,get() 会从流中删除字符,peek() 会保持流的状态不变。

语法

以下是 std::istream::peek() 函数的语法。

int peek();

参数

它不接受任何参数。

返回值

此函数返回输入序列中的下一个字符。

异常

如果抛出异常,则对象处于有效状态。

数据竞争

修改流对象。

示例

在以下示例中,我们将考虑 peek() 函数的基本用法。

#include <iostream>
#include<sstream>
int main()
{
    std::istringstream a("Welcome");
    char x = a.peek();
    std::cout << "Peeked Character : " << x << std::endl;
    return 0;
}

输出

以上代码的输出如下:

Peeked Character : W

示例

考虑以下示例,我们将使用 peek() 函数以及 ignore() 函数。

#include <iostream>
#include<sstream>
int main()
{
    std::string a = "ABC";
    std::istringstream x(a);
    x.ignore();
    char y = x.peek();
    std::cout << "Peeked Character : " << y << std::endl;
    return 0;
}

输出

以下是以上代码的输出:

Peeked Character : B

示例

让我们看一下以下示例,我们将使用 peek() 以及 isalpha() 来检查它是否为字母字符。

#include <iostream>
#include <cctype>
#include<sstream>
int main()
{
    std::string x = "1A2B";
    std::istringstream y(x);
    char a = y.peek();
    if (std::isalpha(a)) {
        std::cout << "Next character is alphabetic: " << a << std::endl;
    } else {
        std::cout << "Next character is not alphabetic: " << a << std::endl;
    }
    return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Next character is not alphabetic: 1
istream.htm
广告

© . All rights reserved.