我試圖在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;
}
預期產量是多少? – 2011-12-28 00:35:25
如果find_X()找不到合適的字符,那麼它返回std :: string :: npos,你應該明確地測試這個(而不是> 0),因爲一些大的字符串會中斷。 – 2011-12-28 08:17:45
您可以通過在stringstream上調用std :: getline()來更簡單地編寫它。 – 2011-12-28 08:18:49