请编写一个fun函数,实现如下功能:将一个字符串中第一个连续数字转换成整数,作为函数值返回,否则返回0(程序的输入输出要有提示) 比如:字符串中的内容为:"abc123 def45gh",则函数的返回值为123。
为什么不写注释?
懒得写。。。
#include <iostream>
#include <string>
using namespace std;
int fun(string str);
int main(void) {
string str = "abc123 def45gh";
cout << fun(str);
return 0;
}
int fun(string str) {
int index = -1;
int score = 0;
for (int i = 0; i < str.length(); i++) {
if ((str[i] >= 48 && str[i] <= 57) && (i + 1 < str.length()) && (str[i + 1] >= 48 && str[i + 1] <= 57)) {
index = i;
break;
}
}
if (index == -1) {
return score;
}
score = str[index] - '0';
for (int i = index + 1; i < str.length(); i++) {
if (str[i] >= 48 && str[i] <= 57) {
score *= 10;
score += str[i] - '0';
} else {
break;
}
}
return score;
}