This repository was archived by the owner on Mar 1, 2026. It is now read-only.
forked from ParosSrl/string-calculator-kata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd.h
More file actions
47 lines (38 loc) · 1.32 KB
/
add.h
File metadata and controls
47 lines (38 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#pragma once
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;
int add(string numbers) {
// Default delimiter is ','
char delimiter = ',';
// Check if a custom delimiter is specified
if (numbers.find("//") == 0) {
delimiter = numbers[2];
// Update numbers to exclude the delimiter specification
numbers = numbers.substr(4);
}
int sum = 0;
// Create a stringstream from the input string
stringstream ss(numbers);
string num, strg;
// Iterate through each line in the input string
while (getline(ss, strg, '\n')) {
// Create a stringstream for the current line
stringstream lineStream(strg);
// Iterate through each number in the line using the specified delimiter
while (getline(lineStream, num, delimiter)) {
int currentNum = stoi(num);
// Check if the current number is negative, and throw an exception if it is
if (currentNum < 0) {
throw runtime_error("negatives not allowed: " + to_string(currentNum));
}
// Add the current number to the sum if it is less than or equal to 1000
if (currentNum <= 1000) {
sum += currentNum;
}
}
}
// Return the sum of valid numbers
return sum;
}