Im trying to make a program that you tipe in any numbers as a string and the
program sums them, like this:
Enter a number:4865
and then it would display 23, becouse 4+8+6+5=23
I managed to do a 3 number example using getch from conio.h library but its a verry stupid way of doing this, but i just didn't know how to do better.
heres the code:
#include <sstream>
std::string myString = 50235;
int myNumber = 0;
std::stringstream myString_ss (myString);
myString_ss >> myNumber;
//safely puts the number into an int
//it's recommended you check if the string IS an int first..
//or it might cause errors
This is not what i had in mind, though i think this is a good way to do it.
How lets say i split an int containing a number 123 into 3 ints, the firts contains the first digit, the second the secont digit etc...
so it would be like this:
int i = 123;
int a,b,c,;
cout<<a (space)<<b(space)<<c(space);
and the program result would be:
1 2 3.
and then i could sum the three ints like this:
int sum = a+b+c;
cout<<sum;
and it would display:
6
EDIT: sorry, i really have to refresh the page before posting
EDIT 2: i dont understand either method and neither works
Ahh.. I didn't understand what you were asking.
Well you can make an array the length of the integer, pick off all the individual integers and place in appropriate array slot (hint - use % and /) then another int, sum would be the total of the array.
string s = "34573456";
int sum = 0;
for(unsignedint x = 0; x < s.size(); x++)
sum += s[x]-48;
//sum will equal 37
The characters 0-9 have ascii values of 48-57. s[x] is of type char, which automatically converts to type int when used in a context expecting an int. So, subtract 48 from the value, and you get the integer value of that numerical character. A bounding clause could also be used to ignore ascii characters outside of 0-9 ie:
string s = "34573456";
int sum = 0;
for(unsignedint x = 0; x < s.size(); x++)
sum += s[x]-48;
//sum will equal 37
The characters 0-9 have ascii values of 48-57. s[x] is of type char, which automatically converts to type int when used in a context expecting an int. So, subtract 48 from the value, and you get the integer value of that numerical character. A bounding clause could also be used to ignore ascii characters outside of 0-9 ie: