0

I'm having trouble figuring out one of my homework problems.

"Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. Read the input as a c-string or a string object. The program should display all the single-digit numbers in the string. For example, if the user enters 2514, the program should display 12, which is (2+5+1+4). The program should also display the highest and lowest digits in the string."

The problem I'm having is figuring out how to add up the integers within the string. My code is below and any help is appreciated, thanks!.

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //Declaring Variables & Character Array:
    int size;
    int sum;
    char integers[size];

    //Gathering Integers:
    cout << "Please enter a series of integers with nothing between them.";
    cin >> integers;

    //Gathering Size of String:
    size = strlen(integers) + 1;

    //Adding up Contents Within String:
    for(int i = 0; i < size; i++)
    {
        if(integers[i] > 0 && integers[i] < 9 && integers != "\0")
        {
           sum = integers[i]++;
        }
    }

    //Outputting Sum:
    cout << sum;

    return 0;
}
2
  • You have to convert each character of the string into a number, and then do the addition using that number. I suspect figuring out how to do so is part of the purpose of your assignment, which means you should try to work that out yourself. Commented Mar 22, 2019 at 0:12
  • Do you know how long the user input will be every time? Or are you not given that information? Commented Mar 22, 2019 at 0:14

3 Answers 3

1

You can use something like this:

std::string integers;

//Gathering Integers:
cout << "Please enter a series of integers with nothing between them.";
cin >> integers;
int sum = 0;

for (char c : integers)
    if (c >= '0' && c <= '9')
        sum += c - '0';

To explain what above code does, I believe first couple of lines are apparent, I will skip to for() loop. This is form of foreach loop used in C++. It grabs character by character from string and stores it in variable (in this case in c), and inside a loop we have normal checking if c is ASCII representation of number 0 to 9. Following that ASCII representation is converted to integer (c - '0').

Your approach is comparing integers with ASCII characters, you can try this:

if(integers[i] >= '0' && integers[i] =< '9' && integers != '\0') {
    sum = integers[i] - `0`;
}

You also have a problem:

integers != "\0"

should be:

integers[i] != '\0'

"" is representation of string and even if you have "" it is an empty string but in contains \0 in it. In the case above "\0" contains '\0\0'. So basically what you want is to comparing single character with \0 where as you are comparing string with \0\0.

Yet another error:

int size;
...
char integers[size];
...
cin >> integers; // SEGFAULT HERE
size = strlen(integers); 

uninitialized variables are undefined behavior in C++ and might contain garbage, from 0 to MAX_INT. You might get segfault if size is 0 and you later try to enter more than 0 characters into integers. You will segfault before you even reach size = strlen().

Another uninitialized variable:

int size;

I actually got 432552 as my output from your program after fixing all those errors mentioned above.

Here is your debugged code:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //Declaring Variables & Character Array:
    int size = 100; // UNINITIALIZED VARIABLE
    int sum = 0;    // UNINITIALIZED VARIABLE
    char integers[size];

    //Gathering Integers:
    cout << "Please enter a series of integers with nothing between them.";
    cin >> integers;

    //Gathering Size of String:
    size = strlen(integers); // +1 ??? why

    //Adding up Contents Within String:
    for(int i = 0; i < size; i++)
    {
        // integers[i] >= 0 is comparing char to int
        // integers[i] <= 9 is comparing char to int
        // ingegers == "\0" is comparing entire string with stirng which contains "\0":s
        // < and > shoudl be <= nad >= to include 0 and 9                                                                                                                                                                                
        if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '\0')
        {
           // sum = integers[i]++; is incrementing character at integer[i]` not `sum`
           sum += integers[i] - '0';
        }
    }

    //Outputting Sum:
    cout << sum;

    return 0;
}

Hah just realized another error you had: strlen() returns length of integer lets say string s="ABCD" is given strlen(s) will return 4, and later in for() loop loop goes from 0 and up to 4 but not including 4 since s[0] = 'A', s[1] = 'B', s[2] = 'c' and s[3] = 'D'.

Ok, so to further explain, characters have digital values as well: enter image description here

If you see all characters have decimal values: here is short table of charcters 0 - 9 from ascii table above:

 Character | Decimal Value
 ----------+--------------
   0       |    48
   1       |    49
   2       |    50
   3       |    51
   4       |    52
   5       |    53
   6       |    54
   7       |    55
   8       |    56
   9       |    57

so by doing this:

 integers[i] - '0'

is basically like saying

 integers[i] - 48

if integer[i] is 8 it will hold decimal value of 56. So 56 - 48 would give integer value of 8

Sign up to request clarification or add additional context in comments.

3 Comments

Don't take this as criticism, but the OP is clearly following some homework task designed to teach, instead of providing the code (without any explanation - which is not helpful in any case,) try in the future to provide some guidance and allow them to figure it out - they are then likely to hit the objective of the task.
@Nim, I do value your input, is this a good way to explain to him what is going on? There were a lot of errors in his code, I tried to explain every one of them as good as posible.
@Gox - explanations are good, however, you should be more reticent about giving code away - the principle here is that the learner has to learn, part of the learning process is also looking in resources for concepts they don't know, if you simply give the code (even with explanations,) the temptation is to simply copy the code and hand it in (am not saying this is what this particular OP will do, but it's there..) So, for next time, merely explain where someone has gone wrong and provide some guidance on where they can look.
1

So there are several problems with your approach, consider the following hints:

  1. Don't read into a char array, instead read from cin into a std::string.
  2. As you iterate through the characters of the string in your for-loop, they are not numbers, instead they are ascii characters. You need to work out how to translate '0' to 0 (hint, ascii characters have numeric values too, perhaps investigate that.)
  3. sum = integers[i]++; this is not how you sum up the numbers..

Comments

0

Using the help from you guys up above, I edited it so that it now works like this:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //Declaring Variables & Character Array:
    int size;
    char integers[size];
    int sum;

    //Small and Large Numbers:
    int small = 9;
    int large = 0;

    //Gathering Integers:
    cout << "Please enter a series of integers with nothing between them.";
    cin >> integers;

    //Gathering Size of String:
    size = strlen(integers) + 1;

    for(int i = 0; i < size; i++)
    {
        if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '\0')
        { 
            if(integers[i] == '0')
                sum += 0;
            if(integers[i] == '1')
                sum += 1;
            if(integers[i] == '2')
                sum += 2;
            if(integers[i] == '3')
                sum += 3;
            if(integers[i] == '4')
                sum += 4;
            if(integers[i] == '5')
                sum += 5;
            if(integers[i] == '6')
                sum += 6;
            if(integers[i] == '7')
                sum += 7;
            if(integers[i] == '8')
                sum += 8;
            if(integers[i] == '9')
                sum += 9;
        }
    }

    cout << sum << endl;


    return 0;
}

1 Comment

this is overkill :( each char has decimal value. char '0' has decimal value of 48, char '1' has decimal value of 49, char '2' is 50 and so on. So what happens if you enter 5 into the string? What decimal value does memory contain?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.