简体   繁体   English

在 getline 字符串中获取字符串

[英]Getting strings within a getline string

Is there a way to traverse a getline string with a normal string.有没有办法用普通字符串遍历 getline 字符串。

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. stringTraverse 需要是“2”,然后是“BIRTH”,直到所有单词都被读取。

you can use sscanf on nextLine.c_str() to get each piece.您可以在 nextLine.c_str() 上使用 sscanf 来获取每一块。 Alternatively put nextLine into a string stream and then read until the stream is done so或者将 nextLine 放入字符串 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 然后读取直到 stream 完成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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