This repository was archived by the owner on Jul 29, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Original file line number Diff line number Diff line change 55using namespace std ;
66
77int add (string numbers) {
8+ // Default delimiter is ','
89 char delimiter = ' ,' ;
10+
11+ // Check if a custom delimiter is specified
912 if (numbers.find (" //" ) == 0 ) {
1013 delimiter = numbers[2 ];
14+ // Update numbers to exclude the delimiter specification
1115 numbers = numbers.substr (4 );
1216 }
17+
1318 int sum = 0 ;
19+ // Create a stringstream from the input string
1420 stringstream ss (numbers);
1521 string num, strg;
22+
23+ // Iterate through each line in the input string
1624 while (getline (ss, strg, ' \n ' )) {
25+ // Create a stringstream for the current line
1726 stringstream lineStream (strg);
27+
28+ // Iterate through each number in the line using the specified delimiter
1829 while (getline (lineStream, num, delimiter)) {
1930 int currentNum = stoi (num);
31+
32+ // Check if the current number is negative, and throw an exception if it is
2033 if (currentNum < 0 ) {
2134 throw runtime_error (" negatives not allowed: " + to_string (currentNum));
2235 }
36+
37+ // Add the current number to the sum if it is less than or equal to 1000
2338 if (currentNum <= 1000 ) {
2439 sum += currentNum;
2540 }
2641 }
2742 }
43+
44+ // Return the sum of valid numbers
2845 return sum;
2946}
You can’t perform that action at this time.
0 commit comments