istream get和getline異同分析

參考文章:
http://blog.163.com/huang_zhong_yuan/blog/static/1749752832010102223333176/

get函數每次可以獲取單個字符,指定長度的字符串等
getline函數每次獲取一行,或者根據指定分隔符分隔提取字符串

get函數原型:
int get();
istream& get ( char& c );
istream& get ( char* s, streamsize n );
istream& get ( char* s, streamsize n, char delim );
istream& get ( streambuf& sb);
istream& get ( streambuf& sb, char delim );
http://www.cplusplus.com/reference/iostream/istream/get/

getline函數原型:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
http://www.cplusplus.com/reference/iostream/istream/getline/

可以看到,兩個函數都能根據指定分隔符提取字符串

區別:
函數get當遇到分隔符後,停止獲取,並將分隔符留在輸入流中,函數getline當遇到分隔符後,停止獲取,但會將分隔符從輸入流中取出。
所以使用get函數的時候,需要手動跳過分隔符,而getline則不需要。

具體示例代碼:
#include <iostream>
#include <string>
#include <sstream>

int main()
{
    int length ;
    std::string st = "Enter,the,name,of,an,existing,text,file:";
    std::istringstream stream(st);
    int i = 0;
    char array[20] = {0};
    while(stream.get(array, 20, ','))
    {
        //獲取當前位置
        length = stream.tellg();

        std::cout << array << std::endl;

        //跳過逗號(,)
        stream.seekg (length + 1, std::ios::beg);
    }

    return 0;
}


發佈了231 篇原創文章 · 獲贊 5 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章