2011-12-28 43 views
1

我試圖在C++中編寫一個簡單的std :: string標記器,並且我無法讓它正常工作。我發現一個在線哪個工作,我明白爲什麼它的作品....但我仍然無法弄清楚爲什麼我原來的一個不是工作。我假設我有一些愚蠢的小東西,我錯過了......我會欣賞一個指向正確方向的指針;謝謝!爲什麼C++字符串標記器不工作

輸入(隨機字符,並用 「\ n」 個 「\ t」 的符號):

"This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G,\nnewline7iuf32\t2f,f3rgb, 43q\nefhfh\nu2hef, wew; wg" 

標記生成器:

size_t loc, prevLoc = 0; 
while((int)(loc = theStr.find_first_of("\n", prevLoc)) > 0) { 
    string subStr = theStr.substr(prevLoc, loc-1);  // -1 to skip the \n 
    cout << "SUBSTR: '" << subStr << "'" << endl << endl; 
    tokenizedStr->push_back(subStr); 
    prevLoc = loc+1; 
} // while 

輸出:

SUBSTR: 'This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G' 

SUBSTR: 'newline7iuf32 2f,f3rgb, 43q 
efhfh 
u2hef, wew; wg' 

SUBSTR: 'efhfh 
u2hef, wew; wg' 

注意,第二「SUBSTR」(顯然)中仍然有換行符(「\ n」)

編譯代碼:

#include <vector.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string> 

using namespace std; 

int main(int argc, char *argv[]) { 

    string testStr = "This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G,\nnewline7iuf32\t2f,f3rgb, 43q\nefhfh\nu2hef, wew; wg"; 
    vector<string> tokenizedStr; 

    size_t loc, prevLoc = 0; 
    while((int)(loc = testStr.find_first_of("\n", prevLoc)) > 0) { 
     string subStr = testStr.substr(prevLoc, loc-1);  // -1 to skip the \n                          
     cout << "SUBSTR: '" << subStr << "'" << endl << endl; 
     tokenizedStr.push_back(subStr); 
     prevLoc = loc+1; 
    } // while                                           

    return 0; 
} 
+0

預期產量是多少? – 2011-12-28 00:35:25

+0

如果find_X()找不到合適的字符,那麼它返回std :: string :: npos,你應該明確地測試這個(而不是> 0),因爲一些大的字符串會中斷。 – 2011-12-28 08:17:45

+0

您可以通過在stringstream上調用std :: getline()來更簡單地編寫它。 – 2011-12-28 08:18:49

回答

3

substr第二個參數是一個尺寸,而不是一個位置。與其說這是這樣的:

testStr.substr(prevLoc, loc-1); 

試試這個:

testStr.substr(prevLoc, loc-prevLoc); 

一旦你解決這個問題,你會遇到的一個問題是,你是不是打印的最後一個子,因爲你停止一旦你沒有找到換行符。所以從最後一個換行符到字符串末尾沒有被存儲。

+0

該死......顯然......謝謝! – DilithiumMatrix 2011-12-28 02:24:51

相關問題