C++ istream::operator>>() 函式



C++ 的std::istream::operator>>()函式是一個提取運算子,用於將格式化資料從字串流物件讀取到變數中。它的工作方式類似於與std::cin一起使用的>>運算子,但它從字串緩衝區中提取資料。

此函式有 3 個多型變體:使用算術型別或流緩衝區或操縱器(您可以在下面找到所有變體的語法)。

語法

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

istream& operator>> (bool& val);
istream& operator>> (short& val);
istream& operator>> (unsigned short& val);
istream& operator>> (int& val);
istream& operator>> (unsigned int& val);
istream& operator>> (long& val);
istream& operator>> (unsigned long& val);
istream& operator>> (long long& val);
istream& operator>> (unsigned long long& val);
istream& operator>> (float& val);
istream& operator>> (double& val);
istream& operator>> (long double& val);
istream& operator>> (void*& val);
or
istream& operator>> (streambuf* sb );
or
istream& operator>> (istream& (*pf)(istream&));
istream& operator>> (ios& (*pf)(ios&));
istream& operator>> (ios_base& (*pf)(ios_base&));

引數

  • val - 它指示儲存提取的字元所表示的值的物件。
  • sb - 它指示指向 basic_streambuf 物件的指標,字元將複製到其控制的輸出序列上。
  • pf - 它指示一個函式,該函式獲取並返回一個流物件。

返回值

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

異常

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

資料競爭

修改 val 或 sb 指向的物件。

示例

讓我們看下面的例子,我們將讀取單個整數。

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    std::string a = "11";
    std::stringstream b(a);
    int x;
    b >> x;
    std::cout << "Result : " << x << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

Result : 11

示例

考慮下面的例子,我們將讀取多個數據型別。

#include <iostream>
#include <sstream>
#include <string>
int main()
{
    std::string a = "11 2.3 TutorialsPoint";
    std::stringstream b(a);
    int x;
    float y;
    std::string z;
    b >> x >> y >> z;
    std::cout << "x : " << x << ", y : " << y << ", z : " << z << std::endl;
    return 0;
}

輸出

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

x : 11, y : 2.3, z : TutorialsPoint

示例

在下面的示例中,我們將讀取整數列表。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
    std::string x = "1 2 3 4 5";
    std::stringstream y(x);
    std::vector<int> a;
    int b;
    while (y >> b) {
        a.push_back(b);
    }
    std::cout << "Result :";
    for (int n : a) {
        std::cout << " " << n;
    }
    std::cout << std::endl;
    return 0;
}

輸出

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

Result : 1 2 3 4 5
istream.htm
廣告