我在 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/