C++分割字符串
#include<iostream>
#include<string>
using namespace std
;
int main(){
string s
;
getline(cin
, s
, ' ');
cout
<< s
<< endl
;
system("pause");
return 0;
}
主要是getline这个函数来实现的。从cin输入数据读入s中,第三个参数以’ '来分隔。 外面加个循环,就能实现对字符串的分隔了。
ps:第三个参数如果用双引号就不对了。回头搞清楚(依稀记得书上说过,好像string对象和字面值不一样)
下面是网上看的,甚至看不懂鬼鬼,回头研究吧,等我学熟练了,特别是那个while循环,看不懂。cout和>>操作符到底是一个什么逻辑,我没有理解。
#include <iostream>
#include <sstream>
using namespace std
;
int main(int argc
, char** argv
) {
istringstream
str(" this is a text");
string out
;
while (str
>> out
) {
cout
<< out
<< endl
;
}
}