用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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM