用getline分割字符串

使用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

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

posted @ 2020-06-26 11:56  黎曼猜想  阅读(1032)  评论(0)    收藏  举报