-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path49_StrToInt.cpp
More file actions
72 lines (55 loc) · 1.08 KB
/
49_StrToInt.cpp
File metadata and controls
72 lines (55 loc) · 1.08 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# include <iostream>
# include <cstdlib>
# include <vector>
# include <string>
using namespace std;
void display_vec(vector<int> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
void display_vec(vector<string> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
int StrToInt(string str)
{
int error = 0;
// empty string
if (str.size() <= 0)
return error;
int flag = 1, i = 0, num = 0;
// sign
if (str[i] == '-')
{
flag = -1;
i++;
}
else if (str[i] == '+')
i++;
// only sign
if (i >= str.size())
return error;
// every digit
while (i < str.size())
{
// illegal digit
if (str[i] < '0' || str[i] > '9')
return error;
num = num * 10 + (str[i] - '0');
i++;
}
return num * flag;
}
int main(int argc, char *argv[])
{
string str = argv[1];
int res;
cout << str << endl;
res = StrToInt(str);
cout << res << endl;
return 0;
}