我正在努力sscanf()从 C++ 代码库中删除调用,并用std::stringstream此处描述的实现替换它们:https : //www.quora.com/Is-there-aC-alternative-to-sscanf。相关代码是:
template<class Char>
class imatch
{
const Char* s;
public:
imatch(const Char* x) :s(x) {}
template<class Stream>
friend Stream& operator >> (Stream& st, const imatch& m)
{
std::basic_string<Char> x;
st >> x; //strip spaces, read chars up to space
if(x!=m.s) st.setstate(st.failbit); //set as "failure" a mismatch
return st;
}
};
Run Code Online (Sandbox Code Playgroud)
然后在我的代码库中:
std::stringstream ss("value = 15"); //the input
int val=0;
ss >> imatch("value") >> imatch("=") >> val;
if(ss)
{ std::cout << …Run Code Online (Sandbox Code Playgroud)