forked from skylarbpayne/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstr_to_int.cpp
More file actions
42 lines (37 loc) · 689 Bytes
/
Copy pathstr_to_int.cpp
File metadata and controls
42 lines (37 loc) · 689 Bytes
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
/**
* Author: Skylar Payne
* Date: December 28, 2014
* Implement a string to int conversion
**/
#include <iostream>
#include <string>
int str_to_int(char* s) {
int sign = 1;
if(*s == '-') {
sign = -1;
++s;
}
int num = 0;
while(*s) {
if('0' <= *s && *s <= '9') {
num = num * 10 + int(*s - '0');
++s;
}
else {
throw "Not a valid integer string!";
}
}
return sign * num;
}
int main(int argc, char** argv) {
if(argc != 2) {
std::cout << "Inappropriate number of arguments. Please provide a number." << std::endl;
return -1;
}
try {
std::cout << str_to_int(argv[1]) << std::endl;
} catch(char* s) {
std::cout << s << std::endl;
}
return 0;
}