如何解析这样的C++;输入字符串 如何解析下面的C++字符串 在以下表格上: string1= 2012-01 //year-month; string2= House; //second sub-field string3= 20; // integer

如何解析这样的C++;输入字符串 如何解析下面的C++字符串 在以下表格上: string1= 2012-01 //year-month; string2= House; //second sub-field string3= 20; // integer,c++,string,parsing,C++,String,Parsing,从下面的stdin 2012-01-23, House, 20 2013-05-30, Word, 20 //might have optional space 2011-03-24, Hello, 25 ... ... so on #包括 #包括 #包括 #包括 使用名称空间std; typedef向量StringVec; //注意:“1,2,3”不读取最后一个“ 无效拆分(StringVec和vsTokens、const string和str、char delim){ i

从下面的
stdin

2012-01-23, House, 20
2013-05-30,  Word,  20    //might have optional space
2011-03-24, Hello,    25
... 
...
so on
#包括
#包括
#包括
#包括
使用名称空间std;
typedef向量StringVec;
//注意:“1,2,3”不读取最后一个“
无效拆分(StringVec和vsTokens、const string和str、char delim){
istringstream iss(str);
字符串标记;
vsTokens.clear();
while(getline(iss、token、delim)){
vsTokens。推回(token);
}
}
空心修剪(标准::字符串和src){
常量字符*空格=“\t\n\v\f\r”;
size\u t iFirst=src.find\u first\u not\u of(空格);
如果(iFirst==字符串::npos){
src.clear();
返回;
}
size\u t iLast=src.find\u last\u not\u of(空格);
如果(iFirst==0)
src.resize(iLast+1);
其他的
src=src.substr(iFirst,iLast iFirst+1);
}
void SplitTrim(StringVec&vs、const string&s){
分裂(vs,s,,);

对于(sisixt t=0;谢谢你的代码。精彩。我想知道,对于C++,通常在处理字符串解析时,这么长吗?)
#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;
typedef vector<string> StringVec;

// Note: "1,2,3," doesn't read the last ""
void Split(StringVec& vsTokens, const string& str, char delim) {
    istringstream iss(str);
    string token;
    vsTokens.clear();
    while (getline(iss, token, delim)) {
        vsTokens.push_back(token);
    }
}

void Trim(std::string& src) {
    const char* white_spaces = " \t\n\v\f\r";
    size_t iFirst = src.find_first_not_of(white_spaces);
    if (iFirst == string::npos) {
        src.clear();
        return;
    }
    size_t iLast = src.find_last_not_of(white_spaces);
    if (iFirst == 0)
        src.resize(iLast+1);
    else
        src = src.substr(iFirst, iLast-iFirst+1);
}

void SplitTrim(StringVec& vs, const string& s) {
    Split(vs, s, ',');
    for (size_t i=0; i<vs.size(); i++)
        Trim(vs[i]);
}

main() {
    string s = "2012-01-23, House, 20 ";
    StringVec vs;
    SplitTrim(vs, s);
    for (size_t i=0; i<vs.size(); i++)
        cout << i << ' ' << '"' << vs[i] << '"' << endl;
}