2

我有以下功能:

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
      }
    }
}

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

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

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

谢谢

4

1 回答 1

2

您可以使用以下代码从末尾删除 '\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
      }
    }
}
于 2013-04-28T13:43:03.773 回答