C++11 从包含其他字符的字符串中提取尾随int 我在C++中从字符串中提取签名int有问题。 假设我有一个字符串“代码> IVSE1234 < /Cord>”,我如何从字符串中提取 1234代码>,而不知道C++中最后一个非数字字符的位置。

C++11 从包含其他字符的字符串中提取尾随int 我在C++中从字符串中提取签名int有问题。 假设我有一个字符串“代码> IVSE1234 < /Cord>”,我如何从字符串中提取 1234代码>,而不知道C++中最后一个非数字字符的位置。,c++11,visual-c++,string-parsing,C++11,Visual C++,String Parsing,仅供参考,我已经尝试了stringstream以及其他人在帖子中建议的词法转换,但是stringstream在词法转换停止工作时返回0 int main() { string virtuallive("Images1234"); //stringstream output(virtuallive.c_str()); //int i = stoi(virtuallive); //stringstream output(virtuallive); int i;

仅供参考,我已经尝试了stringstream以及其他人在帖子中建议的词法转换,但是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;
}
intmain()
{
字符串virtuallive(“Images1234”);
//stringstream输出(virtuallive.c_str());
//int i=stoi(虚拟的);
//stringstream输出(virtuallive);
int i;
i=boost::词法转换(virtuallive.c_str());
//输出>>i;
库特

我如何从字符串中提取1234,而不知道C++中最后一个非数字字符的位置?

你不能。但这个职位并不难找到:

auto last_non_numeric = input.find_last_not_of("1234567890");
char* endp = &input[0];
if (last_non_numeric != std::string::npos)
    endp += last_non_numeric + 1;
if (*endp) { /* FAILURE, no number on the end */ }
auto i = strtol(endp, &endp, 10);
if (*endp) {/* weird FAILURE, maybe the number was really HUGE and couldn't convert */}

另一种可能是将字符串放入
stringstream
,然后从流中读取数字(在向流注入区域设置后,该区域设置将除数字以外的所有内容分类为空白)


当流包含大量数据,并且您希望以相同的方式解释该流中的所有数据时(例如,仅读取数字,而不考虑它可能包含的其他数据),此技术非常有用本,这真的很有效。我已经尝试了Thorney的另一个解决方案,但是结果返回了0。感谢你的帮助,谢谢你的指导。嗨,杰瑞,谢谢你的回复,考虑到我是一个C++新手,需要一些时间来消化你的代码,稍后尝试并尝试理解代码。非常感谢你的帮助
// 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;