【发布时间】:2021-04-17 19:15:32
【问题描述】:
我正在努力从 C++ 代码库中删除 sscanf() 调用,并将其替换为此处描述的 std::stringstream 实现:https://www.quora.com/Is-there-a-C-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;
}
};
然后在我的代码库中:
std::stringstream ss("value = 15"); //the input
int val=0;
ss >> imatch("value") >> imatch("=") >> val;
if(ss)
{ std::cout << "read value = " << val << std::endl; }
else
{ std::cout << "read failed" << std::endl; }
这在构造函数调用中使用类模板参数推导。它工作得很好……在 C++17 中。问题是这段代码需要一路编译回RHEL6,它最多只支持-std=c++0x(C++11的一个子集)。
编写和使用此类的最简洁的方法是什么,以便用户可以轻松地移植他们的sscanf() 调用以使用它,而无需访问 C++17?
【问题讨论】:
-
您真的需要在呼叫站点使用 Char 模板参数吗?我会简单地使用 c_imatch = imatch