### Chess board program not working for large integers

Hi everyone,

I am trying to write a pogram in which first, you are given the description of a chess board (f rows and c columns). After, follows f lines with c numbers each line, meaning every number (from 0 to 9) the amount of coins in every square.

eg: imput << 2 1 (rows and columns)
5 coins on the first square of the first row.
4 coins on the second square of the second row.
output >> 9

here's how i do it:

 ``123456789101112131415161718192021`` ``````#include using namespace std; int main () { long long int f, c, n; long long int a = 0; cin >> f >> c; if (f <= 0 or c <= 0) cout << "0"; else { for (int i = 0; i < f; ++i) { cin >> n; for (int o = 0; n != 0; ++o) { a = a + n%10; n = n/10; } } cout << a; } cout << endl; }``````

brief explanation: once the amount of rows and columns is given, the program reads the next numbers as integers and uses % to obtain every number, which is added up to the counter 'a'.

Now for big numbers like bigger than 20 figures the program doesent seem to work.

If someone could help me I would apreciate it a lot, i have been fighting with this code for 3 days (not much but for a beginner like me looks like a lot :D).

Have a nice day!
Last edited on
Hi
You try this code.
 ``1234567891011121314151617181920212223242526`` ``````#include #include #include using namespace std; int main () { long long int f, c, n; long long int a = 0, k; string s; getline(cin,s); stringstream(s) >> f >> c; if (f <= 0 or c <= 0) cout << "0"; else { for (int i = 0; i < f; ++i) { getline(cin,s); int l=s.length(); for (int o = 0; o < l; ++o) { k = s[o] - '0'; a = a + k; } } cout << a << endl; } cout << endl; }``````
Thanks a lot for such a fast answer.

 ``123`` ``````for (int o = 0; o < l; ++o) { k = s[o] - '0'; a = a + k;``````

i dont really understand the function of k, why is the " - '0' " needed?

Again thanks a lot for helping!
`5` is numer.
So when you have something like this:
`char a = '5'`;
is `a` equal to 5?
No. `a` is equal to 53. Because `'5'` is ASCII representation of number ( http://www.asciitable.com/ ).

If you have `char a = '5'` and you would like to find out what number it is, the simplest method is subtracting '0' (48) from '5' (53) which will result in 5.
Last edited on
The subtraction bit is to convert a character representation of a digit ('0', '1', etc.) to the integer representation (0, 1, etc.)
Again thanks a lot for those fast answers, you helped me a lot!
Topic archived. No new replies allowed.