C++ stringstream 字串分割

#include <sstream>

stringstream:專門用來讀取字串並且處理,常用來做字串分割。

int to string

int n; string s;
cin >> n;
stringstream ss;
ss << n;
ss >> s;
cout << s;

string to int

int n; string s;
cin >> s;
stringstream ss;
ss << s;
ss >> n;
cout << n;

將含有逗號的字串分割

string s, arr[50];
cin >> s;
stringstream ss(s);
int n = 0;
while(getline(ss, arr[n], ',')) n++;
for(int i=0; i<n; i++) cout << arr[i] << ' ';
分享文章!
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。