C++ 中 getline()的定義及應用

getline的兩種定義

1.全局函數,在頭文件 #include<string> 中,函數聲明爲:
- istream& getline ( istream& is, string& str, char delim )
- istream& getline ( istream& is, string& str )


2. istream的成員函數,函數聲明爲:
- istream& getline (char* s, streamsize n ) ; // char *s 表示 char類型的指針,也是char字符數組的首地址,將讀取的內容

                                                                         存入到  char類型的字符數組中
- istream& getline (char* s, streamsize n, char delim )

  • istream的成員函數getline(),終止讀取的條件,根據已讀取的字符的個數來判定,實際上是讀取n-1個字符,因爲最後要爲‘\0’留下一個位置。其他地方二者基本相同。

常用的是第一種,全局函數這種情況getline函數的基本功能 將流 istream& is 中的字符串存到string& str 當中去

  •  全局函數中兩種聲明的區別是第一種加了一個限定符號char delim,默認限定符號爲‘\n’,即讀到一個換行符就終止讀取。
  •   判斷空行的辦法是str.length()==0
  •   判斷輸入結束的辦法是is.eof()

 

函數聲明

   bool getline(istream &in, string &s)

功能說明:

從輸入流讀入一行到變量string s,即使是空格也可以讀入。

–直到出現以下情況爲止:

• 讀入了文件結束標誌

• 讀到一個新行(有重載函數可以指定行分隔符,默認是"\n".)

• 達到字符串的最大長度

–如果getline沒有讀入字符,將返回false,可用於判斷文件是否結束.

int main(int argc,char* argv[])
{
    ifstream ifs;
    ofstream ofs;
    string str;
    ifs.open(argv[1]);
    ofs.open(argv[2]);
    while(getline(ifs,str))
    {
        if(str.at(0)=='#')//過濾特殊的行(此處是#開頭)
            continue;
        ofs<<str<<endl;
    }
    ifs.close();
    ofs.close();
    return 0;
}

 

 

C++依次讀取文件中的字符串——getline()函數的應用

例如文件test.txt中有這麼一段話:I am a boy. You are a girl.

如何一次一個的讀取單詞,即第一次讀取I,第二次讀取am,依次類推。

方法1:

#include <fstream>  
#include <string>  
#include <iostream>  
using namespace std;  

int main()  
{  
     ifstream ifs("test.txt");     // 改成你要打開的文件  
    streambuf* old_buffer = cin.rdbuf(ifs.rdbuf());  

     string read;  
     while(cin >> read)           // 逐詞讀取方法一  
      cout << read;  
     cin.rdbuf(old_buffer);       // 修復buffer  
}  

方法2:

#include <iostream>  
#include <fstream>  
using namespace std;  

int main()  
{  
    ifstream ifs("test.txt");   // 改成你要打開的文件  
    ifs.unsetf(ios_base::skipws);  
    char c;  
    while(ifs.get(c))           // 逐詞讀取方法二  
     {  
       if(c == ' ')  
          continue;  
       else  
          cout.put(c);  
    }  
}  

方法3:

#include <iostream>  
#include <fstream>  
#include <string>  
using namespace std;  

int main()  
{  
  ifstream ifs("test.txt");      // 改成你要打開的文件  
  string read;  
  while(getline(ifs, read, ' ')) // 逐詞讀取方法三  
  {  
    cout << read << endl;  
  }  
}  

 

方法4:

#include <fstream>  
#include <iostream>  
using namespace std;  
int main()  
{  
  ifstream ifs("test.txt");            // 改成你要打開的文件  
  char buffer[256];  
  while(ifs.getline(buffer, 256, ' ')) // 逐詞讀取方法四  
  {  
    cout << buffer;  
  }  
}  


參考:

https://www.cnblogs.com/zhaojk2010/p/5727393.html

https://blog.csdn.net/yulijuanxmu/article/details/77936759

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章