c++11 - 从包含其他字符的字符串中提取尾随 int

标签 c++11 visual-c++ string-parsing

我在 C++ 中从字符串中提取有符号 int 时遇到问题。 假设我有一个 images1234 字符串,如何在不知道 C++ 中最后一个非数字字符的位置的情况下从字符串中提取 1234

仅供引用,我已经按照其他人通过帖子建议的方式尝试了 stringstream 和 lexical_cast,但 stringstream 返回 0,而 lexical_cast 停止工作。

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;
}

最佳答案

How can i extract the 1234 from the string without knowing the position of the last non numeric character in 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 */}

关于c++11 - 从包含其他字符的字符串中提取尾随 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042156/

相关文章:

javascript - 如何在不包含 token 的字符串上调用 split(token) 而不会导致错误?

c++ - 项目中缺少 guiddef.h

visual-c++ - 如何检测CListCtrl选择更改?

c++ - 为什么线程对类变量所做的更改没有影响?

c++ - 循环包含和前向声明类

c# - list 的 supportedOS 设置在幕后实际上做了什么?

f# - 在F#中,是否可以使用tryParse函数来推断目标类型

java - 使用字符串(数字)进行计数

c++ - 我可以返回一个 ofstream 对象来初始化另一个 ofstream 对象吗?

c++ - 显式删除析构函数而不调用 delete