File tree 1 file changed +21
-0
lines changed
1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change 5
5
6
6
// https://stackoverflow.com/questions/29200635/convert-float-to-string-with-precision-number-of-decimal-digits-specified
7
7
// http://www.cplusplus.com/reference/string/stoi/
8
+ // https://stackoverflow.com/questions/3850558/how-to-check-to-ensure-you-have-an-integer-before-calling-atoi
8
9
9
10
// g++ string_to_number.cpp -std=c++11
10
11
@@ -31,5 +32,25 @@ int main(){
31
32
std::string sl = " 1234567890123456" ;
32
33
std::cout << std::stol (sl) << std::endl; // 1234567890123456
33
34
35
+ // when string is not guaranteed to be convertible
36
+ char * pEnd;
37
+ std::string s = " 123" ;
38
+ long num = strtol (s.c_str (), &pEnd, 10 );
39
+
40
+ if (*pEnd == ' \0 ' )
41
+ std::cout << " Convert " << s << " to " << num << " successfully!\n " ;
42
+ else
43
+ std::cout << " Cannot convert " << s << " to number\n " ;
44
+ // Convert 123 to 123 successfully!
45
+
46
+ s = " abc123" ;
47
+ num = strtol (s.c_str (), &pEnd, 10 );
48
+
49
+ if (*pEnd == ' \0 ' )
50
+ std::cout << " Convert " << s << " to " << num << " successfully!\n " ;
51
+ else
52
+ std::cout << " Cannot convert " << s << " to number\n " ;
53
+ // Cannot convert abc123 to number
54
+
34
55
return 0 ;
35
56
}
You can’t perform that action at this time.
0 commit comments