关于从c ++中的字符串中提取带符号的int,我有一个问题。假设我有一个字符串images1234
,则如何1234
在不知道C ++中最后一个非数字字符的位置的情况下从字符串中提取。
仅供参考,我已经尝试通过其他人通过帖子建议的stringstream以及lexical_cast,但是在lexical_cast停止工作时stringstream返回0。
int main()
{
string virtuallive("Images1234");
//stringstream output(virtuallive.c_str());
//int i = stoi(virtuallive);
//stringstream output(virtuallive);
int i;
i = boost::lexical_cast<int>(virtuallive.c_str());
//output >> i;
cout << i << endl;
return 0;
}
另一种可能性是将字符串放入中stringstream
,然后从流中读取数字(在向流中添加将除数字以外的所有内容归类为空格的语言环境)。
// First the desired facet:
struct digits_only: std::ctype<char> {
digits_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
// everything is white-space:
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
// except digits, which are digits
std::fill(&rc['0'], &rc['9'], std::ctype_base::digit);
// and '.', which we'll call punctuation:
rc['.'] = std::ctype_base::punct;
return &rc[0];
}
};
然后代码读取数据:
std::istringstream virtuallive("Images1234");
virtuallive.imbue(locale(locale(), new digits_only);
int number;
// Since we classify the letters as white space, the stream will ignore them.
// We can just read the number as if nothing else were there:
virtuallive >> number;
该技术主要在流包含大量数据并且您希望以相同方式解释该流中的所有数据(例如,仅读取数字,而不管其可能包含的内容)时有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句