Article Directory
1. Integer, Float -> String
A. Function prototype:
B. Analysis
Usually integer conversions are generally accurate, but when floating-point conversions are performed due to precision issues, there may be some deviations in the effective digits.
C. Code
#include<iostream>
#include<cstring>
using namespace std;
int main(){
cout << to_string(123) << endl; // 整型通常无误差 123
cout << to_string(1e-9) << endl; // 0.000000
cout << to_string(123456789.6543210) << endl; // 123456789.654321
}
2. String -> Integer
A. Function prototype:
B. Analysis
If it cannot be converted, return invalid_argument
If it exceeds the range of data conversion, return out_of_range
C. Code
#include<iostream>
#include<cstring>
using namespace std;
int main(){
cout << stoi("123") << endl; // 123
// cout << stoi("aaa") << endl; // invalid_argument
cout << stoll("12345678901") << endl; // 12345678901
// cout << stoi("12345678901") << endl; // out_of_range
}
3. String -> Float
A. Function prototype:
B. Analyze
If the conversion cannot be performed, return Std::invalid_argument
if the converted value is outside the range of the result type, or return std::out_of_range if the underlying function (strtof, strtod, or strtold) sets errno to ERANGE.
c. code
#include<iostream>
#include<cstring>
using namespace std;
int main(){
cout << stof("123.123") << endl; // 123.123
// cout << stof("aa") << endl; // invalid_argument
// cout << stof("1.23e100") << endl; // out_of_range
}