我编写了一些可以读取字符串和字符文字的代码。与普通流读取一样,如果它获取无效数据,则会设置流的 badbit。这应该适用于所有类型的流,包括宽流。将此位粘贴到新标头中:
#include <iostream>
#include <string>
#include <array>
#include <cstring>
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) {
std::array<e, N-1> buffer; //get buffer
in >> buffer[0]; //skips whitespace
if (N>2)
in.read(&buffer[1], N-2); //read the rest
if (strncmp(&buffer[0], sliteral, N-1)) //if it failed
in.setstate(in.rdstate() | 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; //get buffer
in >> buffer; //read data
if (buffer != cliteral) //if it failed
in.setstate(in.rdstate() | 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);
}
这将使输入字符变得非常容易:
std::istringstream input;
double val1, val2;
if (input >>'('>>val1>>','>>val2>>')') //less chars than scanf I think
{
// got them!
}
概念验证 http://ideone.com/IVW7v。现在你可以cin
字符串和字符文字,如果输入不完全匹配,它的行为就像无法正确输入的任何其他类型一样。请注意,这仅匹配字符串文字中不是第一个字符的空格。它只有四个功能,而且都简单得脑残。
EDIT
使用流进行解析是一个坏主意。使用正则表达式。