|
发表于 2022-3-7 18:19:29
|
显示全部楼层
用正则表达式把每一个数字都提取出来,然后求和,就是这样
都C++了,就不要什么都自己写代码了,C++标准库有好多好多的东西,直接用就好
- #include <iostream>
- #include <string>
- #include <regex>
- #include <algorithm>
- using std::cin, std::cout, std::endl;
- using std::string, std::getline;
- using std::regex, std::sregex_token_iterator;
- using std::for_each, std::stoi;
- int main() {
- string line;
- while(getline(cin, line)) {
- regex reg("[+-]?[1-9][0-9]*|0");
- int sum = 0;
- for_each(sregex_token_iterator(line.begin(), line.end(), reg), sregex_token_iterator(),
- [&sum](const string &str) {sum += stoi(str);});
- cout << sum << endl;
- }
- return 0;
- }
复制代码 |
|