Skip to content

Commit ba6e089

Browse files
committed
String to int example
1 parent 40a06e3 commit ba6e089

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Cpp/stringToInt.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <string>
2+
#include <iostream>
3+
#include <climits>
4+
5+
int stringToInteger(const std::string& str)
6+
{
7+
int result = 0;
8+
bool isNegative = false;
9+
int i = 0;
10+
11+
//check str is negative or not
12+
if(str[0] == '-')
13+
{
14+
isNegative = true;
15+
i++;
16+
}
17+
18+
for(; i<str.size(); ++i)
19+
{
20+
if(std::isdigit(str[i]))
21+
{
22+
23+
// to check the overflow is exist or not
24+
// if INT_MAX > (result * 10 + (str[i] - '0')) then there is a overflow
25+
// if(result * 10 + (str[i] - '0') > INT_MAX) // but this will not work
26+
// because result * 10 + (str[i] - '0') if result is cause overflow then there
27+
// will be undefined behaviour so it is good idea to compare it with result
28+
29+
if(result > (INT_MAX - (str[i] - '0')) / 10)
30+
{
31+
std::cout<<"overflow detected"<<std::endl;
32+
return isNegative ? INT_MIN : INT_MAX;
33+
}
34+
35+
result = result * 10 + (str[i] - '0');
36+
}
37+
else
38+
return 0;
39+
}
40+
41+
if(isNegative)
42+
result = -result;
43+
44+
return result;
45+
}
46+
47+
int main()
48+
{
49+
std::cout<<stringToInteger("123")<<std::endl;
50+
std::cout<<stringToInteger("99999999999999999999999999");
51+
52+
std::endl(std::cout);
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)