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 から行を 1 行ずつ読み取り、getline特別な文字列に「出会う」まで使用します。その後、次の行に対して特別な処理を行う必要があります。特別な文字列は次のとおりです。

; -------- Special -------------------- Windows で対応する行 line を読むと、 '\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 に答える