鑑於a
和b
是內置類型的變量,你無法定義自己的用戶定義運算的流他們(標準庫中已經提供了這樣的功能)。
你可以只寫出來與你想要的行爲的代碼...
int a, b;
char eq, gt;
// this is probably good enough, though it would accept e.g. "29 = > 37" too.
// disable whitespace skipping with <iomanip>'s std::noskipws if you care....
if (iFile >> a >> eq >> gt >> b && eq == '=' && gt == '>')
...
OR包裝a
和b
成class
或struct
,並提供用戶自定義的運營商所提供。有很多SO問題的答案解釋瞭如何編寫這樣的流媒體功能。
或寫支持功能...
#include <iomanip>
std::istream& skip_eq_gt(std::istream& is)
{
char eq, gt;
// save current state of skipws...
bool skipping = is.flags() & std::ios_base::skipws;
// putting noskipws between eq and gt means whatever the skipws state
// has been will still be honoured while seeking the first character - 'eq'
is >> eq >> std::noskipws >> gt;
// restore the earlier skipws setting...
if (skipping)
is.flags(is.flags() | std::ios_base::skipws);
// earlier ">>" operations may have set fail and/or eof, but check extra reasons to do so
if (eq != '=' || gt != '>')
is.setstate(std::ios_base::failbit)
return is;
}
...然後用它像這樣...
if (std::cin >> a >> skip_eq_gt >> b)
...use a and b...
此功能 「作品」,因爲流的目的是接受「io操縱器」函數重新配置流的某個方面(例如,std::noskipws
),但對於要調用的函數,只需匹配(輸入)io操縱器的原型:std::istream& (std::istream&)
。
一個小班似乎是你最簡單的賭注。 – chris