简体   繁体   中英

Getting strings within a getline string

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

string nextLine;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM