【问题标题】:get unread section of istringstream获取 istringstream 的未读部分
【发布时间】:2013-07-12 02:25:21
【问题描述】:

我有一个测试,我从std::istringstream 中获取字符。我想获取在测试期间未阅读的std::istringstream 部分。 std::istringstream::str() 函数返回整个字符串,而不仅仅是未读部分。

如何获取字符串的这一部分?

【问题讨论】:

  • std::getline(mystringstream, rest_of_string)
  • @MooingDuck 这不会一直读到……行尾吗? (直到istringstreameof。)
  • 哎呀。 std::getline(mystringstream, rest_of_string, 0); 将一直读取,直到找到更接近的 NULL 或 EOF。

标签: c++ c++11


【解决方案1】:

假设您没有在此行之前手动设置输入位置指示器:

std::string unread = stream.eof()  ?  "" : stream.str().substr( stream.tellg() );

【讨论】:

  • 这适用于 std::istringstream 的所有实现吗?
  • @Graznarak 是的,这里没有具体的实现。
  • @DyP 我不太明白。我没有使用rdbuf()->str(),我知道它会返回整个字符串。
  • @DyP 对,我在想别的东西 ;)
  • @0x499602D2 这不适用于带有空字符串的 std::istringstream。至少在 VS2012 中没有。
【解决方案2】:

我认为最简单的方法是将istringstream的读取缓冲区推送到字符串流:

void test(std::istringstream& iss)
{
  /* Test code */
}

int main()
{
   std::istringstream iss;
   std::stringstream not_readed_buffer;
  std::string not_readed;

   test( iss );

   if( iss )
   {
       not_readed_buffer << iss.rdbuf();
       not_readed = not_readed_buffer.str();    
   }
}

查看this answer for a similar question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 2010-12-25
    • 2021-02-28
    • 2016-08-08
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2017-08-26
    相关资源
    最近更新 更多