有没有办法用普通字符串遍历 getline 字符串。
string nextLine;
getline(fin, nextLine);
nextLine = "2 BIRTH OCT 30 1998";
string stringTraverse = ?;
stringTraverse 需要是“2”,然后是“BIRTH”,直到所有单词都被读取。
您可以在 nextLine.c_str() 上使用 sscanf 来获取每一块。或者将 nextLine 放入字符串流中,然后读取直到流完成为止
stringstream s(nextLine);
while (s >> some_string)
//do stuff with string piece
以下是一个伪逻辑(未经测试,但应该看起来像那样):
size_t word = 0, currentSpace;
while(string::npos != (currentSpace = nextLine.find(" ")))
{
stringTraverse = nextLine.substr(word, currentSpace);
while(nextLine[++currentSpace] == " ");
word = currentSpace;
// ... use it
}
if(nextLine[word] != 0)
stringTraverse = nextLine.substr(word);