Hi every one
There is a question that says: let the user input any integer number and then separate it and then add the individual numbers together for the summation
and here what I did .. but there is a problem .. some times the last number become less by 1 ... for example if I enter 1234 .. it displays 1 2 3 3
here is the code:
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main ()
{
int sum = 0;
string input;
cout << "Enter any integer number" << endl;
cin >> input;
cout<<"The Individual digits of " << input << " are : ";
for (size_t i = 0; i < input.length(); i++) {
cout << input.at(i) << " ";
stringstream ss(input.substr(i, 1)); //generates a string with the current diget as its content
int x;
ss >> x;
sum += x;
}
cout << "The Sum is :" << sum << endl;
return 0;
}
you cant. double is as most precision as possible.
There's still long double though. And __float128 in gcc.
And using stringstreams is unnecessary in this case. You can directly convert an ASCII digit character to a number by substracting 48 from it. And even then you would only have to do that in the first place when you wanted to add the digits of a floating point number, the example hamstermann gave works just fine with integers.