Reputation: 99
Hi I'm really new to c++ and I wanted to write a code which receives a number from user and sums its digits and keeps doing that until it gets a one-digit number and returns it as a result. But I noticed that when my number is large (like 15 digits long), the wrong number is stored in the variable i declared for storing user input. What do I do?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int get_sum(long x) {
cout << x<<endl;
if (x < 10) {
return x;
}
else {
string num_in_str = to_string(x);
long result=0;
for (int i = 0; i < num_in_str.size(); i++) {
int digit = num_in_str[i] - '0';
result += digit;
}
return get_sum(result);
}
}
int main()
{
long input;
cin >> input;
int final_result = get_sum(input);``
cout << final_result;
}
Upvotes: 1
Views: 1985
Reputation: 3551
Integer data types in C++ can store numbers up to certain limit. In particular, depending on platform and compiler, "long" can be 32 or 64 bit, and store up to 2^31-1 or 2^63-1. If you want to process numbers of an arbitrary precision, I'd suggest to read each input as string, and process it character-by character, like this:
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string s;
while (std::getline(std::cin, s)) {
// parse string
long sum = 0;
for (std::size_t i = 0; i < s.length(); ++i) {
if (std::isdigit(s[i]))
sum += s[i] - '0';
else
break;
}
std::cout << sum << std::endl;
if (sum < 10) break;
}
return 0;
}
Upvotes: 1