代码之家  ›  专栏  ›  技术社区  ›  user3344484

如何在C++中解析定界符后的部分疑难解答?

  •  0
  • user3344484  · 技术社区  · 7 年前

    最近刚开始学习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

    2 回复  |  直到 7 年前
        1
  •  3
  •   Barmar    7 年前

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

    find() 返回匹配开始的索引,而不是结束的索引。您需要添加调用时要跳过的字符串的长度 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++;
        }
    }
    
        2
  •  0
  •   Community CDub    3 年前

    此外,请注意,使用中描述的折叠机制,属性值可能跨越多条线 https://www.rfc-editor.org/rfc/rfc5545#section-3.1

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

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