首页 > 其他 > 详细

用getline分割字符串

时间:2020-06-26 12:18:11      阅读:125      评论:0      收藏:0      [点我收藏+]

使用getline和stringstream分割字符串:

 1 #include <iostream>
 2 #include <string>
 3 #include <sstream>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     string s;
11     getline(cin,s);
12     stringstream ss(s);
13     vector<string> vs;
14     while(getline(ss,s, ) ) // 这里只能使用单字符,不能使用字符串“”此类
15     {
16         cout << s << "-";
17         vs.push_back(s);
18     }
19     cout << endl;
20     for(auto x:vs)
21     {
22         cout << x << " ";
23     }
24     cout << endl << vs.size() << endl;
25     return 0;
26 }

输入:  1 2 3 4 5 

输出:

 -1-2-3-4-5-
  1 2 3 4 5
 6

可知其遇到一个空格则认为有一个元素,而不管空格前是否有字符。

用getline分割字符串

原文:https://www.cnblogs.com/limancx/p/13194336.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!