C++ istream::ignore() 函式



C++ 的std::istream::ignore()函式用於跳過或忽略輸入流中的字元。它常用於清除不需要的字元或處理讀取預期資料後包含額外字元的輸入。

如果指定了字元數或分隔符,它將跳過這麼多字元,或者直到遇到分隔符為止。

語法

以下是std::istream::ignore()函式的語法。

istream& ignore (streamsize n = 1, int delim = EOF);

引數

  • n − 表示要提取的最大字元數。
  • delim − 表示分隔符字元。

返回值

此函式返回 basic_istream 物件 (*this)。

異常

如果丟擲異常,則物件處於有效狀態。

資料競爭

修改流物件。

示例

讓我們看下面的例子,我們將跳過固定數量的字元。

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("ABTutorialsPoint.");
    x.ignore(2);
    std::string y;
    std::getline(x, y);
    std::cout << "Result :  " << y << std::endl;
    return 0;
}

輸出

上述程式碼的輸出如下:

Result :  TutorialsPoint.

示例

考慮下面的例子,我們將使用ignore()函式跳過數字之間的空格。

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("11 12 23");
    int a, b, c;
    x >> a;
    x.ignore();
    x >> b;
    x.ignore();
    x >> c;
    std::cout << "Result : " << a << ", " << b << ", " << c << std::endl;
    return 0;
}

輸出

以下是上述程式碼的輸出:

Result : 11, 12, 23

示例

在下面的例子中,我們將跳過字元,直到找到分隔符。

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("11,23,34");
    x.ignore(11, ',');
    std::string a;
    std::getline(x, a, ',');
    std::cout << "Result : " << a << std::endl;
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Result : 23
istream.htm
廣告
© . All rights reserved.