2016-12-05 125 views
-2

的特定部位我有以下內容輸入文件:讀取和解析文件

Tstart: 13:51:45 
Tend: 13:58:00 

,我想有單獨的字符串的時間戳結尾。到目前爲止,我已經寫了以下內容:

// open the info file 
    if (infile.is_open()) 
    { 
     // read the info regarding the played video 
     string line; 
     while (getline(infile, line)) 
     { 
      istringstream iss(line); 
      string token; 
      while (iss >> token) 
      { 
       string tStart = token.substr(0, 6); 
       string tEnd = token.substr(7,2); 
       cout << tStart << tEnd<< endl; 
      } 

     } 
     infile.close(); 
    } 
    else 
     cout << "Video info file cannot be opened. Check the path." << endl; 

,我得到下面的輸出:

Tstart 
13:51:5 
terminate called after throwing an instance of 'std::out_of_range' 
    what(): basic_string::substr: __pos (which is 7) > this->size() (which is 5) 

我理解錯誤說什麼,但我無法找到用C這樣做的另一種方式++ 。

任何人有想法?

+0

你爲什麼使用'substr'? – LogicStuff

+0

您沒有按照您的意願閱讀文件。我懷疑你是複製了代碼而沒有完全理解它。如果您顯示實際文件,則您執行'substr()'的第一個標記爲「Tstart:」。調試器會向您顯示正在讀取的內容。 – stefaanv

+0

@LogicStuff因爲我只想要文件中的時間戳,而不是其他的時間戳。這是該文件中字符串的「子字符串」。 –

回答

1

字符串line將是一行文字。首先它將是「Tstart:13:51:45」,並且在下一次迭代中將是「Tend:13:58:00」。

字符串token將成爲以空格分隔的line的一部分。所以,如果line是「Tstart:13:51:45」,那麼在第一次迭代中令牌將是「Tstart:」,在第二次迭代中將是「13:51:45」。這不是你需要的。

而是內while環路我建議您尋找與string::find一個空格,然後用string::substr服用空間之後的一切:

bool is_first_line = true; 
string tStart, tEnd; 

while (getline(infile, line)) 
{ 
    int space_index = line.find(' '); 

    if (space_index != string::npos) 
    { 
     if (is_first_line) 
      tStart = line.substr(space_index + 1); 
     else 
      tEnd = line.substr(space_index + 1); 
    } 

    is_first_line = false; 
} 

cout << tStart << tEnd << endl; 

如果不是事先哪行具有值,那麼我們就可以知道仍然擺脫內循環:

string tStart, tEnd; 

while (getline(infile, line)) 
{ 
    int space_index = line.find(' '); 

    if (space_index != string::npos) 
    { 
     string property_name = line.substr(0, space_index); 

     if (property_name == "Tstart:") 
      tStart = line.substr(space_index + 1); 
     else if (property_name == "Tend:") 
      tEnd = line.substr(space_index + 1); 
    } 
} 

cout << tStart << tEnd << endl; 
+0

啊,非常感謝。我試圖在不知道哪一行是第一行,哪一行是第二行的情況下,我認爲我不需要它,因爲在while循環中我依次讀取它。但是,我現在看到了。再次感謝。 –

+0

感謝這篇文章的第二部分,那正是我想要的! –