0

This is my code:

#include <iostream>
#include <string>
#include <sstream>

int main() {

    std::string userInput;
    std::getline(std::cin, userInput);

    int sum;
    int result;
    std::string numDigit;
    bool space = true;

    for (int i = 0; i < userInput.length(); i++) {

        if (isdigit(userInput[i]) && space) {

            numDigit += userInput[i];
            space = false;
        }else if(isdigit(userInput[i]) && !space) {

            numDigit += userInput[i];

        }else if (!isdigit(userInput[i]) && !space) {

            std::stringstream(numDigit) >> result;
            sum += result;
            numDigit = "";
            result = 0;
            space = true;

        }

        std::cout << sum;

    }

}

If i input 1 2 3 with space, it should ouput sum = 6, but instead it output many digits of number why is it like that ? (sorry I'm beginner of c++)

8
  • 1
    Are you aware of the difference between the value 0 and the internal representation of "0", which is (as ASCII, as usual on a lot of current systems) 48? Commented Feb 4, 2017 at 14:00
  • The right tool to solve such problems is your debugger. You should step through your code line-by-line before asking on Stack Overflow. For more help, please read How to debug small programs (by Eric Lippert). At a minimum, you should [edit] your question to include a Minimal, Complete, and Verifiable example that reproduces your problem, along with the observations you made in the debugger. Commented Feb 4, 2017 at 14:04
  • 1
    @RadLexus - "0" is a string literal, consisting of the two characters '0' and '\0'. Commented Feb 4, 2017 at 14:14
  • @RadLexus - aside from the typo, what's your point? The code does not rely on the details of the character encoding; it constructs a string, and uses a stream extractor to get the numeric value that the text in that string represents. In that regard, the code is just fine. Commented Feb 4, 2017 at 14:17
  • 1
    @ShadowLegend - there's some confusion here; the overall structure of your code is fine, and that point about the difference between '0' and 0, while true, isn't relevant here. Commented Feb 4, 2017 at 14:46

1 Answer 1

2

You are using your variables sum and result without initializing them.

When you are using any compiler, you cannot assume that variables will be automatically initialized to zero. So, if you use an uninitialized variable, the behavior of your program will be undefined, it might be just nice the value you want, or it will be filled with garbage values like 80123901723012, -190283812791, etc...

int sum = 0;
int result = 0;

Declare a variable and initialize it to zero is always a good practice.


EDIT :

The problem your code have is:
1. you should only output sum after for loop end.
2. your should check for i <= userInput.length() instead of checking for less than only.

modified code:

#include <iostream>
#include <string>
#include <sstream>

int main() {

    std::string userInput;
    std::getline(std::cin, userInput);

    int sum = 0;
    int result = 0;
    std::string numDigit = "";
    bool space = true;

    for (int i = 0; i <= userInput.length(); i++) {

        if (isdigit(userInput[i]) && space) {

            numDigit += userInput[i];
            space = false;
        }
        else if (isdigit(userInput[i]) && !space) {

            numDigit += userInput[i];

        }
        else if (!isdigit(userInput[i]) && !space) {

            std::stringstream(numDigit) >> result;
            sum += result;
            numDigit = "";
            result = 0;
            space = true;
        }
    }
    std::cout << "sum = " << sum << std::endl;

}


Thanks for pointing out my mistake Pete, I've made the correction to my post.

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

6 Comments

"When you are using Visual Studio..." -- in fact, when you are using any compiler you can't assume that auto variables of builtin types will be initialized to 0.
@Zohou Zhi Hua, bro thanks for your reply and i tried to initialize the variable to 0 as u said but the output did not meet my expectation, as i enter 1 2 3, it outputs 01133
@ShadowLegend hi, I've fixed your bug and edit my answer, check it out.
Oh i see, output the sum after loop solve the problem thanks, but I'm sorry to bother again to ask what's behind it and why it output many digits if i output the sum inside the loop? It should be output like 1, 3, 6 instead of long unrecognize digit right ?
if you want to output 1, 3, 6, then you should put you std::cout << sum; after you set space to true ( the last else if), you are getting the strange numbers because you write twice for each number. When the compiler reads '1', it do numDigit += userInput[i], set space to false and output sum (which is still 0). When the compiler reads ' ' it stringstream numDigit into result and add result to sum, then output sum (now sum becomes 1). same for the '2' and '3'.
|

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.