Search code examples
c++getlineistringstream

Read lines from istringstream ,without '\r' char at the end


I have a following function :

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

I read the lines from std::istringstream line by line,using getline ,until i "meet" special string after which i should do some special processing for the next lines. The special string is:

; -------- Special -------------------- When I read the corresponding line line in windows it ends with '\r' :

(; -------- Special --------------------\r) In Linux no '\r' appears at the end. Is there a way to read the lines consistently without distinguish if it is linux or windows?

Thanks


Solution

  • You can remove the '\r' from the end using this code:

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

    You can wrap this into a function if you want to:

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

    Integrated into your function:

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