用c++ #include <stdio.h> int hecheng(char m[]) { int result = 0; int i = 0; while (m[i] != '\0') { if (m[i] >= '0' && m[i] <= '9') { result = result * 10 + m[i] - '0'; } i++; } return result;}int main() { char s[] = "#&1*3(1)&4"; int result = hecheng(s); printf("%d\n", result); return 0;}
时间: 2024-03-25 14:38:31 浏览: 14
这段代码是 C 语言的代码,如果你需要在 C++ 中使用,需要进行一些修改。以下是修改后的代码:
```c++
#include <iostream>
using namespace std;
int hecheng(char m[]) {
int result = 0;
int i = 0;
while (m[i] != '\0') {
if (m[i] >= '0' && m[i] <= '9') {
result = result * 10 + m[i] - '0';
}
i++;
}
return result;
}
int main() {
char s[] = "#&1*3(1)&4";
int result = hecheng(s);
cout << result << endl;
return 0;
}
```
在 C++ 中,需要使用 `iostream` 头文件来进行标准输入输出操作,因此我们使用 `cout` 代替了 `printf`。
此外,我们也可以使用 `string` 类型来代替字符数组,代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int hecheng(string m) {
int result = 0;
int i = 0;
while (i < m.length()) {
if (m[i] >= '0' && m[i] <= '9') {
result = result * 10 + m[i] - '0';
}
i++;
}
return result;
}
int main() {
string s = "#&1*3(1)&4";
int result = hecheng(s);
cout << result << endl;
return 0;
}
```
在这个版本的代码中,我们使用了 `string` 类型来代替字符数组,并且使用 `length()` 方法来获取字符串的长度。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)