Skip to content

Commit 51cb667

Browse files
committed
add 014_Parse-Strings2Num.cpp
1 parent c56e5b8 commit 51cb667

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

014_Parse-Strings2Num.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/// Description: atoi vs stoi (parsing string to int or float)
2+
/// Author: Pritesh Gohil - priteshbgohil [at] gmail [dot] com
3+
4+
#include<iostream>
5+
6+
int main(int argc, char const *argv[]) {
7+
std::cout << "atoi presentations" << '\n';
8+
9+
// ASCII to integer : atoi (come from C language)
10+
// bad choice because on failure it returns "0"
11+
std::cout << "atoi(\"1234\") = " << atoi("1234") << '\n';
12+
std::cout << "atoi(\"failes\") = " << atoi("failes") << '\n'; //0 when fails
13+
14+
15+
// string to integer : std::stoi (since C++11)
16+
std::cout << "stoi(\"-1234\") = " << std::stoi("-1234") << '\n';
17+
std::cout << "stoi(\"12xy34\") = " << std::stoi("12xy34") << '\n';
18+
try{
19+
std::cout << "stoi(\"failes\") = " << std::stoi("failes") << '\n';
20+
}
21+
catch (const std::exception& ex){
22+
std::cout << "Couldnt convert: " << ex.what() << '\n';
23+
}
24+
// stol, stoll, stof, stod, stold (long, long long, float, double, long double)
25+
std::cout << "stof(\"123.456\") = " << std::stof("123.456") << '\n';
26+
27+
return EXIT_SUCCESS;
28+
}

0 commit comments

Comments
 (0)