-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings_toInt.cc
More file actions
58 lines (55 loc) · 1.42 KB
/
strings_toInt.cc
File metadata and controls
58 lines (55 loc) · 1.42 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
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int
main (int argc, char *argv[])
{
string sentence;
string word;
cout << "Enter the integers one at a time. End with \"#\"" << endl;
do {
cin >> word;
sentence += " ";
sentence += word;
} while (word.compare("#") != 0);
int total = 0;
int indx = 0;
#if 0
bool started = false;
int length = 0;
for (size_t i {}; i < sentence.length(); i++)
{
if (isdigit(sentence[i])) {
if (started) {
length++;
} else {
started = true;
indx = i;
length = 1;
}
} else {
if (length > 0) {
auto num = atoi(sentence.substr(indx, length).c_str());
cout << num << endl;
total += num;
}
started = false;
}
}
#endif
int start = 0;
do {
if ((indx = sentence.find(" ", start)) == std::string::npos) {
indx = sentence.length();
}
auto num_str = sentence.substr(start, indx - start);
if (!num_str.empty()) {
auto num = atoi(num_str.c_str());
cout << num << endl;
total += num;
}
start = indx + 1;
} while ((indx != std::string::npos) && (start < sentence.length()));
cout << "Total: " << total << endl;
}