c++11 - How to convert every element of a string to int -


i trying total sum of every digit of big number stored in string variable. first thing convert each element int , add total sum. question how can convert element of string int? tried using std::stoi got compiler error.

here's code anyway:

std::string x = "7825394359371498287"; int sum = 0; (int = 0; < x.size(); ++i) {     sum += std::stoi(x[i]); } 

the problem std::stoi wants string , give single character.

this problem can solved knowing text encoding used can convert digit character corresponding number. take example common encoding system ascii, if see table in provided link tell character '7' have ascii value 55, while character '0' have value 48. should tell number 7 character '7' have subtract '0' '7' (i.e. 55 - 48), so:

sum += x[i] - '0'; 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -