簡體   English   中英

如何編寫 `std::istream` 運算符

[英]How to write an `std::istream` operator

如果流包含意外內容、在預期之前結束或未完全消耗,我如何編寫讀取std::istream並設置適當標志的函數?

為了具體起見,假設我希望流包含一串字母字符,后跟一個分隔符,然后是一些數字,例如foo:55 我想閱讀類似的東西

struct var {
  std::string name;
  double value;
};

從溪流。 我當然可以將運算符寫為

std::istream& operator>>(std::istream& s, var& x) {
  std::string str;
  s >> str;
  size_t sep = str.find(':');
  x.name  = str.substr(0,sep);
  x.value = atof(str.substr(sep+1).c_str());
  return s;
}

但是我可以不將流內容復制到字符串嗎? 此外,這不適用於空格,因為str不會包含整個流內容。

大約一周前我問了一個類似的問題,但沒有得到回應,可能是因為我在boost::program_options上下文中對其進行了框架化,而此類問題在這里似乎沒有得到太多關注。

您可以使用std::getline而不是s >> str來讀取':' ,然后將數字直接讀入double ,如下所示:

std::istream& operator>>(std::istream& s, var& x) {
    // Skip over the leading whitespace
    while (s.peek() == '\n' || s.peek() == ' ') {
        s.get();
    }
    std::getline(s, x.name, ':');
    s >> x.value;
    return s;
}

演示。

為什么不讓流為您完成工作。 您可以使用getline()>>istream::ignore()來讀入輸入。

std::istream& operator>>(std::istream& s, var& x) {
    // get the string part and through out the :
    std::getline(s, x.name, ':');
    // get the number part
    s >> x.value;
    // consume the newline so the next call to getline won't include it in the string part
    s.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
    return s;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM