我可以告诉一个std :: string是否使用stringstream的数字? [英] Can I tell if a std::string represents a number using stringstream?
本文介绍了我可以告诉一个std :: string是否使用stringstream的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
显然,这是为了显示一个字符串是否是数字,例如12.5== yes,abc== no。但是,我得到一个没有reguardless的输入。
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;}
推荐答案
使用 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 using good
later.
#include <sstream>
#include <iostream>
int main()
{
std::istringstream ss("2");
double d = 0.0;
if(ss >> d) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}
}
这篇关于我可以告诉一个std :: string是否使用stringstream的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文