Skip to content

Commit 2ca4289

Browse files
when string is not guaranteed to be convertible
1 parent b2f6c36 commit 2ca4289

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

string_to_number.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
//https://stackoverflow.com/questions/29200635/convert-float-to-string-with-precision-number-of-decimal-digits-specified
77
//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
89

910
//g++ string_to_number.cpp -std=c++11
1011

@@ -31,5 +32,25 @@ int main(){
3132
std::string sl = "1234567890123456";
3233
std::cout << std::stol(sl) << std::endl; //1234567890123456
3334

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+
3455
return 0;
3556
}

0 commit comments

Comments
 (0)