There is a variable of the string type, the string entered by the user from the keyboard is written to it. It is necessary to calculate the sum of all numbers in this line.

The problem is that it is not possible to translate a character digit into a digital digit. I tried using the atoi function, but it gives the wrong result.

My code is:

 string s; //code code... cin>>s; //code code... for(int i=0;i<s.length();i++) { cout<<s[i]<<" "; if((int)s[i]>47 && (int)s[i]<58) { count++; sum+=atoi(&s[i]); } } 
  • one
    Please provide your code with atoi (). - BuilderC
  • one
    To convert a decimal digit from a character representation to a binary, simply subtract the character '0' from its character representation. - avp

5 answers 5

And offhand, for learning:

 int summ = 0; for (int i=0; i < myString.length(); ++i) { char c = myString[i]; summ += c - '0'; } 

True for sure you will need to add verification. Although you have already done it:

 string s; //code code... cin>>s; //code code... for(int i=0;i<s.length();i++) { cout<<s[i]<<" "; if((int)s[i]>47 && (int)s[i]<58) { sum += s[i] - '0'; } } 
  • And why without - '0' does not work? What prevents 0? - Comfmore
  • Since the char code is generally hidden behind a char type variable (in your case these are codes from 48 - '0' and 57 - '9', in order to convert from char to real in the simplest way, you need to subtract the code from the source code to zero, we actually did. - Dex
  • 2
    All right To check whether a character is a digit, you can (and well) use the isdigit () function from cctypes. - skegg
  • 2
    "I suspect that behind the atoi function this algorithm is hidden." atoi () searches for the beginning of the number (skips the "spaces"), takes into account the sign and stops at the first non-digit, and also multiplies the accumulated amount by 10 before adding. And the rest is similar. - avp
  • one
    @mikillskegg, thanks for the clarification, I don’t know much about С , I don’t know much about libraries. - Dex

Atoi converts a string to a number. A character is not a string. The code will be like this:

 ... int summ = 0; //переменная в которой будет сумма всех цифр int i = 0; for (; i < myString.length(); ++i) { char buff[2]; //массив который будет хранить один символ buff[0] = myString[i]; buff[1] = '\0' //символ конца строки summ += atoi(buff); } ... 
  • but it works without the line buff [1] = '\ 0', why is it needed? - Comfmore
  • 2
    atoi () takes a string, and the string must end with a binary zero . You "and without the line buff [1] = '\\ 0'" worked only because it (binary zero) happened to be there. - avp
  • one
    You can, of course, so. Only somehow it turned out cumbersome. - skegg
  • Yes, the correct (taking comments into account) answer was given by @Dex. It seems that the author of the question did not understand him. I explained about the end of the line. - avp

In general, summing up the proposals of previous authors, I propose such a code

 #include <iostream> #include <cctype> using namespace std; int strsum (const string & str ) { int sum = 0, len = str.length(); for (int i = 0; i < len; i++) if (isdigit(str[i])) sum += str[i] - '0'; return sum; } int main() { string st; cin >> st; cout << strsum (st) << endl; return 0; } 

Another way you can ( ideone ):

 string s = "12345"; transform(s.begin(), s.end(), s.begin(), [](char c){return c-'0';}); int sum = accumulate(s.begin(), s.end(), 0); cout << sum << endl; 

but this is only in case all the characters are digits.

    here, like the same question is being discussed ...
    here

     /*-----------------------------------------------------------*/ //вот мой вариант(только для char) #include<iostream> using namespace std; int conv(char c){ return c-'0'; } //для конвертации string'a предлагаю использовать перегрузку для вводимого типа //после чего возвращаемый результат посимвольно конвертируется и добваляется к //возвращаемому результату. 
    • Seem, there is another little discussed. - skegg
    • one
      There you need to count the sum of the DIGITS that are in the line, i.e. all other characters should be ignored => check each character, whether it is a digit. - skegg