【问题标题】:Read lines from istringstream ,without '\r' char at the end从 istringstream 读取行,末尾没有 '\r' 字符
【发布时间】:2013-04-28 13:26:10
【问题描述】:

我有以下功能:

void process (std::string str)
{
    std::istringstream istream(str);
    std::string line;
    std::string specialStr("; -------- Special --------------------\r"); // win
    //std::string specialStr("; -------- Special --------------------"); //linux
    while (getline(istream,line))
    {
      if (strcmp(specialStr.c_str(), line.c_str()) != 0)
      {
          continue;
      }
      else
      {
         //special processing
      }
    }
}

我使用 getline 逐行读取 std::istringstream 中的行,直到我“遇到”特殊字符串 之后我应该对下一行进行一些特殊处理。 特殊字符串是:

; -------- Special -------------------- 当我在 windows 中读取相应的行时,它以 '\r' 结尾:

(; -------- Special --------------------\r) 在 Linux 中,末尾不会出现“\r”。 有没有办法在不区分是linux还是windows的情况下一致地读取行?

谢谢

【问题讨论】:

  • 您是否以二进制模式打开了流?
  • std::string str; // 是一个参数 std::istringstream isaStream(str);//这样我打开了stringstream
  • 你从哪里得到str的内容? (你可以发布一些代码,你知道的)
  • 我得到 str 作为参数。我会发布一些代码 - 你是对的
  • @jrok - 我已按照您的要求更新了代码

标签: c++ getline istringstream


【解决方案1】:

您可以使用以下代码从末尾删除“\r”:

if(line[line.length() - 1] == '\r') line = line.substr(0, line.length() - 1);

如果你愿意,你可以把它包装成一个函数:

std::istream& univGetline(std::istream& stream, std::string& line)
{
    std::getline(stream, line);
    if(line[line.length() - 1] == '\r') line = line.substr(0, line.length() - 1);
    return stream;
}

集成到您的功能中:

void process (std::string str)
{
    std::istringstream istream(str);
    std::string line;
    std::string specialStr("; -------- Special --------------------");

    while (univGetline(istream,line))
    {
      if (strcmp(specialStr.c_str(), line.c_str()) != 0)
      {
          continue;
      }
      else
      {
         //special processing
      }
    }
}

【讨论】:

  • 是的-这是可能的-谢谢。但我更喜欢调用一些内置函数来摆脱/忽略'\r'字符
猜你喜欢
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多