Suppose there is a number 123. You need to add its numbers, that is, 1 + 2 + 3 (= 6).

Interested in using which function in stdio.h it can be done, and if not, then with what library?

  • 2
    Under each task from laboratory work of library functions you will not save enough. Write with your hands. - VladD

2 answers 2

I understand that the input is a number, not a string.

int n = 123; // число на входе int r = 0; while(n > 0){ int last = n % 10; // последняя цифра (% - остаток от деления) n = n /= 10 // уберем цифру r += last; } 

In r we get the result.

  • There are at least two errors in the code. - KoVadim 3:49 pm
  • @KoVadim first: n = n - (n / 10); instead of n / = 10; and the second? (Negative numbers do not take) - alexlz
  • @KoVadim, and the first is that the author does not consider negative numbers? - avp
  • with negative numbers is a good point. I'm about a forgotten semicolon. - KoVadim
  • I admit mistakes. The code is written on the knee to demonstrate the method. - Dmitry Lepeshkin

There is an ancient trick - because all the digits go in a row in all encodings (? I have not met others in any case), then from the symbol you can get a digit from it '0', it is not particularly tied to the language (we were shown on Pascal). For exact implementation, you need to know what your string is stored in.

And stdio.h is pure si as far as I remember, definitely not visual c ++

  • stdio.h - can be used in C ++ as well as cstdio - Janycz
  • Yes, I know something, I just noted that the tags do not correspond to the essence of the question, although as it turned out he did not understand him correctly) - aknew
  • Not every visual c ++ is a c ++ :) (for those who are in the tank - visual c ++ - there is no such language, there is a studio. On the other hand, visual c ++ - it can be both native and cli) - KoVadim
  • C ++, but with its own ATL extensions that other compilers do not understand - aknew