给定一串字符,我怎样才能遍历它并将该字符串中的所有数字分配给一个整数变量,而忽略所有其他字符?
我想在已经读入一串字符时执行此任务gets()
,而不是在读取输入时执行此任务。
给定一串字符,我怎样才能遍历它并将该字符串中的所有数字分配给一个整数变量,而忽略所有其他字符?
我想在已经读入一串字符时执行此任务gets()
,而不是在读取输入时执行此任务。
unsigned int get_num(const char* s) {
unsigned int value = 0;
for (; *s; ++s) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
return value;
}
编辑:这是该功能的更安全版本。如果s
是NULL
或根本不能转换为数值,则返回 0。UINT_MAX
如果字符串表示大于 的值,则返回UINT_MAX
。
#include <limits.h>
unsigned int safe_get_num(const char* s) {
unsigned int limit = UINT_MAX / 10;
unsigned int value = 0;
if (!s) {
return 0;
}
for (; *s; ++s) {
if (value < limit) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
else {
return UINT_MAX;
}
}
return value;
}
这是一种简单的 C++ 方法:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char* argv[]) {
istringstream is("string with 123 embedded 10 12 13 ints", istringstream::in);
int a;
while (1) {
is >> a;
while ( !is.eof() && (is.bad() || is.fail()) ) {
is.clear();
is.ignore(1);
is >> a;
}
if (is.eof()) {
break;
}
cout << "Extracted int: " << a << endl;
}
}
从标准 C 库中查找strtol
函数。它允许您找到字符数组中为数字的部分,并指向不是数字的第一个字符并停止解析。
您可以使用sscanf
: 它的工作方式类似于scanf
但在字符串(字符数组)上。
sscanf
可能对你想要的东西有点过分,所以你也可以这样做:
int getNum(char s[])
{
int ret = 0;
for ( int i = 0; s[i]; ++i )
if ( s[i] >= '0' && s[i] <= '9' )
ret = ret * 10 + (s[i] - '0');
return ret;
}