Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // demo: sum of elements in range, validation
- // 2026-03-05
- // tested on Win with g++
- // oldschool
- #include <cstdlib>
- #include <cstdio>
- #include <ctime>
- // error handling
- #include <exception>
- #include <stdexcept>
- // I/O handling
- #include <iostream>
- #include <sstream>
- // containers
- #include <vector>
- // configuration
- #define LOW 10
- #define HIGH 99
- #define MAX_SIZE 1000
- #define COLUMNS 20
- using namespace std;
- // value in [low; high] or invalid_argument thrown
- void validateRange(int value, int low, int high){
- if(value < low || value > high)
- throw invalid_argument(string("Value in [") + to_string(low) + "; " + to_string(high) + "] required");
- }
- // stream clean or invalid_argument thrown
- void validateStream(istream &in){
- if(in.fail()){
- in.clear();
- in.ignore(256, '\n');
- throw invalid_argument("Bad input!");
- }
- }
- // vector with n random elements in [LOW; HIGH]
- vector<int> generate(unsigned n){
- validateRange(n, 1, MAX_SIZE);
- vector<int> v;
- for(int i = 0; i < n; ++i)
- v.push_back(LOW+rand()%(HIGH-LOW+1));
- return v;
- }
- // data to stdout
- void print(vector<int> data){
- cout << "Data: ";
- for(int i = 0; i < data.size(); ++i){
- if(i % COLUMNS == 0)
- cout << endl;
- cout << data[i] << " ";
- }
- cout << endl;
- }
- // sum all from data[a] to data[b]
- int computeSum(vector<int> data, int a, int b){
- validateRange(a, 1, data.size());
- validateRange(b, 1, data.size());
- int sum = 0;
- for(int i = a; i <= b; ++i){
- sum += data[i-1];
- }
- return sum;
- }
- int main(){
- try {
- // init
- srand(time(NULL));
- // continue computations
- while(1){
- try {
- // input size and range for sum
- int n = 0, a = 0, b = 0;
- cout << "Enter size n and range [a; b] all in [1; " << MAX_SIZE << "]: ";
- cin >> n >> a >> b;
- //cout << cin.good() << cin.fail() << cin.bad() << cin.eof() << endl;
- validateStream(cin); // throws if invalid
- // proceed to computations
- vector<int> v = generate(n);
- print(v);
- int sum = computeSum(v, a, b); // may throw, try before printing
- cout << "Sum: " << sum << endl;
- } catch (invalid_argument& e){
- cout << e.what() << endl;
- }
- }
- } catch(...){ // should never happen
- cout << "Uncaught exception!" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment