我可以使用 stringstream 判断 std::string 是否表示数字吗?
显然,这应该用于显示字符串是否是数字,例如“12.5”==是,“abc”==否。然而,无论输入如何,我都会得到一个结果。
std::stringstream ss("2");
double d; ss >> d;
if(ss.good()) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}
Apparently this is suposed to work in showing if a string is numerical, for example "12.5" == yes, "abc" == no. However I get a no reguardless of the input.
std::stringstream ss("2");
double d; ss >> d;
if(ss.good()) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要使用good()!测试流是否失败:
Good 告诉您是否设置了 eofbit、badbit 或 failurebit,而fail() 告诉您有关 badbit 和 failurebit 的信息。你几乎从不关心 eofbit,除非你已经知道流失败了,所以你几乎不想使用 good。
请注意,如上所述,直接测试流完全等同于:
相反,!ss 等同于 ss.fail()。
将提取组合到条件表达式中:
完全等同于:
但是,您可能想测试完整的字符串是否可以转换为双精度型,这有点复杂。使用已经处理所有情况的 boost::lexical_cast 。
Don't use good()! Test if the stream is failed or not:
Good tells you if any of eofbit, badbit, or failbit are set, while fail() tells you about badbit and failbit. You almost never care about eofbit unless you already know the stream is failed, so you almost never want to use good.
Note that testing the stream directly, as above, is exactly equivalent to:
Conversely, !ss is equivalent to ss.fail().
Combining the extraction into the conditional expression:
Is exactly equivalent to:
However, you probably want to test if the complete string can be converted to a double, which is a bit more involved. Use boost::lexical_cast which already handles all of the cases.
如果您想检查
字符串
是否只包含一个数字而没有其他内容(除了空格),请使用:ss >> std::ws
对于接受带有尾随空格的数字(例如"24 "
)非常重要。ss.eof()
检查对于拒绝像"24 abc"
这样的字符串非常重要。它确保我们在读取数字(和空格)后到达字符串的末尾。测试工具:
输出:
If you want to check whether a
string
contains only a number and nothing else (except whitespace), use this:The
ss >> std::ws
is important for accepting numbers with trailing whitespace such as"24 "
.The
ss.eof()
check is important for rejecting strings like"24 abc"
. It ensures that we reached the end of the string after reading the number (and whitespace).Test harness:
Output:
您应该使用
istringstream
以便它知道它正在尝试解析输入。另外,直接检查提取的结果,而不是稍后使用good
。You should use an
istringstream
so that it knows it's trying to parse input. Also, just check the result of the extraction directly rather than usinggood
later.