Im having problems with a function of mine. I was just practicing playing with c++ strings, and most of the program works just fine, but after i tried to add a function to calculate the Digit Sum of the numbers in the string, i encountered some weird behaviour.
If i just input the string to be 1, the digit sum is 49, 2 is 50, 3 is 51, and so on. It doesn't really make sense, and the code looks fine to me.
Code:#include <iostream> #include <string> int ZeroTest(std::string str); int EvenTest(std::string str); int OddTest(std::string str); int StrTotal(std::string str); int main() { int ZeroCount = 0, EvenCount = 0, OddCount = 0, Total = 0; std::string str; std::cout << "Enter string to test: "; std::cin >> str; std::cout << std::endl; ZeroCount = ZeroTest(str); EvenCount = EvenTest(str); OddCount = OddTest(str); Total = StrTotal(str); if((ZeroCount + EvenCount + OddCount) == str.size()) { std::cout << "Number of zeroes : " << ZeroCount << std::endl; std::cout << "Number of evens : " << EvenCount << std::endl; std::cout << "Number of odds : " << OddCount << std::endl << std::endl; std::cout << "String total is : " << Total << std::endl; std::cout << "String size is : " << str.size() << std::endl; } else { std::cerr << "String size error" << std::endl; } std::cin.ignore(2); return 0; } int ZeroTest(std::string str) { int i = 0, ZeroCount = 0; for(i; i < str.size(); i++) { if(str[i] == '0') { ZeroCount++; } } return(ZeroCount); } int EvenTest(std::string str) { int i = 0, EvenCount = 0; for(i; i < str.size(); i++) { if(str[i] % 2 == false && str[i] != '0') { EvenCount++; } } return(EvenCount); } int OddTest(std::string str) { int i = 0, OddCount = 0; for(i; i < str.size(); i++) { if(str[i] % 2 == true) { OddCount++; } } return(OddCount); } int StrTotal(std::string str) { int i = 0, Total = 0; while(i < str.size()) { Total = Total + str[i]; i++; } return(Total); }



LinkBack URL
About LinkBacks





Okay, that's a bit far-fetched, but what about hexadecimal?