I'm working on this program, it asked me to compute the sum of all numbers in a string. For example:
Input: There are 10 chairs, 4 desks, and 2 fans.
Output: 16
Explanation: 10 4 2 = 16
My program is like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "There are 10 chairs, 4 desks, and 2 fans.";
int sum = 0;
for(int i = 0; i < str.size(); i )
{
if(str[i] >= 0 && str[i] <= 9)
sum = (int)str[i];
}
cout << sum << endl;
}
I don't understand why the output of my program is 0
, can someone explain what's wrong with my program. Thank you
CodePudding user response:
Alternatively you could use regex, because everyone loves regex.
int main() {
std::string str = "There are 10 chairs, 4 desks, and 2 fans.";
std::regex number_regex("(\\d )");
auto begin = std::sregex_iterator(str.begin(), str.end(), number_regex);
auto end = std::sregex_iterator();
int sum = 0;
for (auto i = begin; i != end; i) {
auto m = *i;
sum = std::stoi(m.str());
}
std::cout << sum << "\n";
}
CodePudding user response:
You should use ascii code to find the numbers in string
. the 0 ascii
code is 48 and 9 is 57. after find the number in string
you should make whole number for example 10 is 1 and 0. and you should make string
with value "10" and use stoi
to convert it to int
.
int main()
{
string str = "There are 10 chairs, 4 desks, and 2 fans.";
int sum = 0;
string number;
bool new_number = false , is_number ;
for (int i = 0; i < str.size(); i )
{
// if you use ascii it is good.
//but if you use other character encodings.you should use if (str[i] >= '0' && str[i] <= '9')
if (str[i] >= 48 && str[i] <= 57)
{
number = str[i];
if (!(str[i 1] >= 48 && str[i 1] <= 57))
{
sum = stoi(number);
number = "";
}
}
}
cout << sum << endl;
}