在从std ::字符串类型到模板t类型的转换中
我在这个论坛上发现了用户Ben Voigt的以下片段:
//forward declaration
template<typename T>
T getline_as(std::istream& s);
template<>
std::string getline_as<std::string>(std::istream& s)
{
std::string str;
std::getline(s,str);
return str;
}
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert(getline_as<std::string>(s));
T value;
convert >> value;
return value;
}
我正在寻找一种处理Convert&gt; gt; gt; gt;的方法的方法。值;
。我的目标是 要迭代用户正确插入给定输入的请求:
int main()
{
std::cout << "Please enter a number: ";
double number{getline_as<double>(std::cin)};
}
我的想法是创建do-do-while
loop getline_as_as ,但我无法使其正常工作。
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert;
T value;
do
{
convert(getline_as<std::string>(s));
}
while(!(convert >> value));
return value;
}
I've found on this forum the following snippet witten by user Ben Voigt:
//forward declaration
template<typename T>
T getline_as(std::istream& s);
template<>
std::string getline_as<std::string>(std::istream& s)
{
std::string str;
std::getline(s,str);
return str;
}
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert(getline_as<std::string>(s));
T value;
convert >> value;
return value;
}
I am looking for a way to handle possible failures of convert >> value;
. My goal would be
to iterate the request to the user to make it insert a given input correctly:
int main()
{
std::cout << "Please enter a number: ";
double number{getline_as<double>(std::cin)};
}
My idea was to create a do-while
loop inside getline_as
but I can't make it work.
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert;
T value;
do
{
convert(getline_as<std::string>(s));
}
while(!(convert >> value));
return value;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std :: stringstream convert(...);
是一个构造函数调用,但是尝试转换(...);
创建流是非法的(它需要流到Overloadoperator()
,它不做)。convert = std :: stringstream(...)
可以正常工作,但是我只是完全重新创建流。您还应该使用只读
std :: Isringstream
,因为您从不写任何东西。我还做了一些化妆品的更改,最终得到以下:
std::stringstream convert(...);
is a constructor call, but trying to doconvert(...);
after the stream is created is illegal (it would require the stream to overloadoperator()
, which it doesn't do).convert = std::stringstream(...)
would work, but I'd just completely recreate the stream.You also should use a read-only
std::istringstream
, since you never write anything to it.I also made some cosmetic changes and ended up with following: