【问题标题】:Getting strings within a getline string在 getline 字符串中获取字符串
【发布时间】:2011-07-15 02:19:33
【问题描述】:

有没有办法用普通字符串遍历getline字符串。

string nextLine;

getline(fin, nextLine);

nextLine = "2 BIRTH OCT 30 1998";

string stringTraverse = ?;

stringTraverse 需要是“2”,然后是“BIRTH”,直到读完所有单词。

【问题讨论】:

  • std::getline 与此无关。特别是因为您立即覆盖您刚刚从“fin”(无论是什么)检索到的字符串。第二行完全无关紧要。

标签: c++ string getline


【解决方案1】:

您可以在 nextLine.c_str() 上使用 sscanf 来获取每个部分。或者将 nextLine 放入字符串流中,然后读取,直到流完成为止

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

【讨论】:

  • 为什么不只是stringstream s(nextLine);
  • @Kerrek,感谢您指出这一点,不知道我为什么这样做
【解决方案2】:

以下是伪逻辑(未经测试,但应该看起来像那样):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2016-07-10
    • 2015-07-07
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多