Hi, I'm a student, finish the first course. Gave 10 tasks, very simple, but one thing I do not quite understand.
The specified non-empty text includes only numbers and letters. Determine whether it satisfies the following property: the text is a decimal notation of a multiple of 9.
Should I work with line items like with numbers? Those. if "123", then this is 1, 2, 3? If so, how?
Knowing that you can work with char as with an int, I did this:
int if_div_by_9 (char str[], int n) { int num = 0; for (int i = 0; i < n; i++) { num = num * 10; num = num + str[i]; } if ((num % 9) == 0) return true; return false; } But at the same time, "1" in the line will not be 1. I understand that ASCII code will be used. If you need to work with numbers from a string, then what about letters? I could write a function that returns a pointer to a new array, in which there are no letters, but I still do not know how to work with numbers, but not with their code. And I'm not sure that I understand the condition of this school assignment.
UPD:
int if_div_by_9 (char str[], int n) { int num = 0; for (int i = 0; i < n; i++) { if ('0' <= str[i] && str[i] <='9') { num *= 10; num += (str[i] - '0'); } } cout << num << endl; if ((num % 9) == 0) return true; return false; }
int if_div_by_9(...) { ... return 0; }int if_div_by_9(...) { ... return 0; }(C-code), orbool if_div_by_9(...) { ... return false; }bool if_div_by_9(...) { ... return false; }(C ++ code). Well, 'D' - '0' == D (if D is a digit) is a requirement of the C standard (C ++), i.e. does not depend on the coding. - andy.37