- Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N values. For example: “Please enter the number of values you want to sum:” 3 “Please enter some integers (press '|' to stop):” 12 23 13 24 15 | “The sum of the first 3 numbers ( 12 23 13 ) is 48.” Handle all inputs. For example, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector.
- Modify the program from exercise 8 to write out an error if the result cannot be represented as an int.
So in exercise 9 it says to write out an error message if the result cannot be represented as an int, but if I'm only adding up integers here the only thing I can think of here that would cause a number to not be able to be represented as an int would be if there's some integer overflow and the integer goes above INT_MAX or below INT_MIN but how exactly can I detect this?
This is my code:
#include<vector>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<stdexcept>
using namespace std;
int main()
{
int N = 0;
vector<int> values;
cout << "Please enter the number of values you want to sum." << '\n';
cin >> N;
cout << "Please enter some numbers" << '\n';
for (int tempnum; cin >> tempnum; )
{
values.push_back(tempnum);
}
if (N > values.size())
{
cout << "How am I gonna add up more numbers than you gave me?" << '\n';
}
else
{
int total = 0;
for (int i = 0; i < N; i++)
{
total += values[i];
}
}
}
But I can't just check if total is above or below INT_MAX or INT_MIN because INT_MAX +1 or something returns some random negative value so I'm not really sure how to do this