开发者

Getting strings within a getline string

Is there a way to traverse a getline string with a normal string.

string nextLi开发者_StackOverflow社区ne;

getline(fin, nextLine);

nextLine = "2 BIRTH OCT 30 1998";

string stringTraverse = ?;

stringTraverse needs to be "2", then "BIRTH", until all the words are read.


you can use sscanf on nextLine.c_str() to get each piece. Alternatively put nextLine into a string stream and then read until the stream is done so

stringstream s(nextLine);
while (s >> some_string)
    //do stuff with string piece


Following is a pseudo logic (not tested, but should look like that):

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜