排查如何在 C++ 中解析定界符后的部分?

Troubleshooting how to parse the part after the delimiter in C++?

最近刚开始学习C++。 我正在尝试读取以下格式的 ics 文件:

BEGIN:VEVENT
UID:2179:203860:1:002:1:person
DTSTAMP:20170921T080000Z
SUMMARY;LANGUAGE=en-ca:BIG CITY
LOCATION:CANADA
DTSTART;TZID=Eastern Standard Time:20170914T183000
DTEND;TZID=Eastern Standard Time:20170914T203000
RRULE:FREQ=WEEKLY;UNTIL=20171201T235959;BYDAY=TH
CLASS:PUBLIC
PRIORITY:5
TRANSP:OPAQUE
STATUS:CONFIRMED
SEQUENCE:0
END:VEVENT 

我所做的是读取每一行并调用一个字符串来查找特定的分隔符,获取紧跟其后的部分,并将其放入一个向量中。 这是我读取文件的方法:

void SimpleCalendar::initialize(){
    int counter = 0;
    string getLine;
    ifstream readFile;
    readFile.open("cal.ics");

if(readFile.fail()){
    throw FileException("Error! Cannot open the file.");
}

while(!readFile.eof()){
    readFile >> getLine;
    size_t summ = getLine.find("SUMMARY;LANGUAGE=en-ca:");
    if (summ != string::npos){
        course.push_back(getLine.substr(summ+1));
        cout << course[counter] << endl;
        counter++;
    }
}

它应该输出的是:BIG CITY 相反,我得到这个 -> SUMMARY;LANGUAGE=en-ca:BIG

不要使用>>,它只读取一个单词(以空格结尾)。使用 getline() 阅读整行。

find() returns匹配开始的索引,而不是结束。您需要在调用 substr().

时添加要跳过的字符串的长度
while (readFile.getline(getLine)) {
    size_t summ = getLine.find("SUMMARY;LANGUAGE=en-ca:");
    if (summ != string::npos){
        course.push_back(getLine.substr(summ + sizeof "SUMMARY;LANGUAGE=en-ca:"));
        cout << course[counter] << '\n';
        counter++;
    }
}

此外,请注意 属性 值可能会使用 https://www.rfc-editor.org/rfc/rfc5545#section-3.1

中描述的折叠机制跨越多行

换句话说,长摘要将表示为

SUMMARY:bla bla bla...
 continuation of bla bla bla