Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to make a simple code that starts with entering random letters and numbers
Then the program collects the numbers only

I have a problem with the combination

What I have tried:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
    string serialcode="a98991G343m163R77Eqc\n";

    int i=0;
    int hjg;
    cout<<serialcode;
    int the_sum=0;
    while (i<21)
    {

        if(isdigit(serialcode[i]))
        the_sum+=serialcode[i];

        i++;
    }

    cout<<the_sum;



     return 0;
}
Posted
Updated 24-Dec-21 3:31am
v2
Comments
191 A 24-Dec-21 9:04am    
the total is not correct how can i fix this code?

You need to understand that a character digit is not its base value. It is a printable representation of a number. So to accumulate the values of these numbers you first need to convert them to their base integral value. Fortunately with single characters it is simply a matter of subtracting the character '0' from them. So change your code to read:
C++
the_sum += serialcode[i] - '0';


Also your while expression should use the length attribute of the string, rather than a fixed value:
C++
while (i < serialcode.length())
 
Share this answer
 
v2
Comments
191 A 24-Dec-21 9:28am    
thank you very much
This line
the_sum+=serialcode[i];
should be
the_sum+= serialcode[i] - '0';


If you are working with string, then better use the capabilities of sting:
int main()
{
    string serialcode="a98991G343m163R77Eqc\n";

    cout<<serialcode;
    int the_sum=0;
    for (int i= 0; i < serialcode.length(); i++)
    {

        if(isdigit(serialcode[i]))
            the_sum+= serialcode[i] - '0';
    }

    cout<<the_sum;

     return 0;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900