1
int main()
{
    int sum = 0, value = 0;
    while (std::cin >> value)
        sum += value;
    std::cout << "Sum is: " << sum << std::endl;
    return 0;
}

So this code takes values from the user and adds them. I don't understand what makes it reach end of file. I tested it multiple times and found that when I use larger numbers (9999999999) it ends faster, but when I put in just 1s it never ends.

1
  • Do you know that an int has a maximum possible value? And if you exceed it, you get a negative result. Its because an int is 32 bits or 64 bits depending upon your PC architecture and represents a range of values from negative to positive using two's complement representation. Google search for int overflow. Commented Oct 17, 2018 at 1:49

2 Answers 2

2

You are experiencing integer overflow.

More specifically, the bool operator on std::istream returns false because the stream failed to read the big value into int.

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

Comments

0

Blake. The issue is that integers can actually only be so big. The range for a regular int is -32,767 to 32,767; the range of a long int is -2,147,483,647 to 2,147,483,647, etc.. I'm sure there is a list online where you can find the different ranges (I don't have them memorized off the top of my head).

Anyways, I believe your issue is that your int sum is getting too big, and it's breaking your program. Furthermore, I'd recommend having a way to close out of your while loop, so that your program doesn't have the potential to go on forever; you could do this with something like: if(value == -1) break;

Enjoy your studies!

2 Comments

Nearly correct. But overflowing sum is not Undefined but Unspecified (I think could be wrong) so its not going to cause the program to break. But your point about the size of integer is absolutely correct. When your use operator>> to read an integer and it does not fit into an integer then the read fails. When a read fails it sets the bad bit on the stream. When the bad bit of the stream is set the while expression will become false and thus the loop will stop.
Oh wow, that makes sense. Thank you for the correction! As you can see by my score, I'm pretty darn new to this stuff myself.

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.