考虑到先决条件,这实际上非常容易。我有这三个函数,我把它们放在某个地方的标题中。这些允许您输入字符文字和字符串文字。我一直不太明白为什么这些不是标准的。
#include <iostream>
//These are handy bits that go in a header somewhere
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) {
e buffer[N-1] = {}; //get buffer
in >> buffer[0]; //skips whitespace
if (N>2)
in.read(buffer+1, N-2); //read the rest
if (strncmp(buffer, sliteral, N-1)) //if it failed
in.setstate(std::ios::failbit); //set the state
return in;
}
template<class e, class t>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& cliteral) {
e buffer(0); //get buffer
in >> buffer; //read data
if (buffer != cliteral) //if it failed
in.setstate(std::ios::failbit); //set the state
return in;
}
//redirect mutable char arrays to their normal function
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
return std::operator>>(in, carray);
}
考虑到这些,剩下的就很简单了:
in>>'x'>>'='>>data.first>>','>>'y'>>'='>>data.second;
证明在这里
对于更复杂的情况,您可能想要使用std::regex
or boost::regex
,或者可能是真正的词法分析器/解析器。