1.getline()函數的定義:
istream& getline(istream& is,string & str, char delim = '/n')
其中 istream 是輸入流,getline()函數從輸入流中讀取數據
str爲字符串,存取從輸入流中讀取的數據
delim爲分隔符,遇到分隔符時,將已讀取到的數據存入str中,默認分隔符爲'/n',也可以定義自己的分隔字符
例子:
#include "iostream"
using namespace std;
#include "string"
#include "sstream"
int main()
{
string str;
getline(cin,str,'*');
cout << str << endl;
system("pause");
return 0;
}
程序運行後會要求我們輸入:我們輸入 1234*5678
程序輸出結果爲:
遇到我們設置的結束符時 讀取結束將讀取結果傳給str
例子2:
getline()常用來分隔字符數據,比如我們由123/456/789,我們想要將這些字符按 '/' 分隔並進行輸出
#include "iostream"
using namespace std;
#include "string"
#include "sstream"
int main()
{
string str;
while (getline(cin, str, '/'))
{
cout << str << " ";
}
cout << "已經跳出循環" << endl;
system("pause");
return 0;
}
輸入 123/456/789 我們發現並不能如期輸出我們想要的結果,輸出爲
而且沒有跳出循環,而是等待cin繼續輸入;這是因爲 getline()函數的返回值爲 istream& ,在這裏即爲 cin ,所以 while 循環會 判斷cin是否有效,而只有輸入不結束,cin是持續有效的,只是沒遇到 結束符 '/' ,沒有讀取到 str中罷了;所以 跳不出while循環,實際中也不能這麼用,那麼想要實現上述功能應該怎麼做呢?
我們引入 stringstream, 將字符串轉化爲 輸入流類,進而採用getline()函數進行分割
stringstream 類是 istream的子類,所以可以當做 getline()函數第一個參數的輸入(因爲子類是特殊的父類)
如下:
#include "iostream"
using namespace std;
#include "string"
#include "sstream"
int main()
{
string str;
string tmp;
cin >> tmp;
stringstream ss(tmp);//用字符串類初始化輸入輸出流
while (getline(ss, str, '/'))
{
cout << str << " ";
}
cout << "已經跳出循環" << endl;
system("pause");
return 0;
}
擴展:
stringstream類還常常用來做類型轉換
如:
將字符串"12345"轉爲整型12345
#include "iostream"
using namespace std;
#include "string"
#include "sstream"
int main()
{
int a;
string s1 = "123456";
stringstream ss(s1);
ss >> a;
cout << a << endl;
system("pause");
return 0;
}
輸出結果爲 123456
注:1.如果在轉化過程中需要用到同一個 stringstream 對象,則在再次使用時需要進行 claer()操作,
clear()這個名字讓很多人想當然地認爲它會清除流的內容, 實際上它並不清空任何內容,它只是重置了流的狀態標誌。
2.stringstream 的 str() 將stringstream流中的內容拷貝一份字符串格式的內容
2.cin.getline()函數
cin.getline(char* str,int N,char delim);
從標準輸入流中讀取數據,如果沒有遇到讀取結束標誌符,默認結束符爲'/n'
則在讀取到N-1個字符時停止讀取,因爲最後一個字符爲'/0';如果遇到則讀取結束。將讀取到的內容存入 C型字符串中
例子:
#include "iostream"
using namespace std;
int main()
{
char tmp[80];
cin.getline(tmp,6,'/0');
cout << tmp;
system("pause");
return 0;
}
輸入:12345678
輸出爲:12345