int类型转换到string类型:
在http://en.cppreference.com/上给出了如下实例代码(以浮点型为例):
#include <iostream>
#include <string>
int main()
{
double f = 23.43;
std::string f_str = std::to_string(f);
std::cout << f_str << '\n';
}
output:
23.430000
string类型转换到int类型:
c语言转换形式:
在http://en.cppreference.com/上给出了如下实例代码:
#include <iostream>
#include <cstdlib>
int main()
{
const char *str1 = "42";
const char *str2 = "3.14159";
const char *str3 = "31337 with words";
const char *str4 = "words and 2";
int num1 = std::atoi(str1);
int num2 = std::atoi(str2);
int num3 = std::atoi(str3);
int num4 = std::atoi(str4);
std::cout << "std::atoi(\"" << str1 << "\") is " << num1 << '\n';
std::cout << "std::atoi(\"" << str2 << "\") is " << num2 << '\n';
std::cout << "std::atoi(\"" << str3 << "\") is " << num3 << '\n';
std::cout << "std::atoi(\"" << str4 << "\") is " << num4 << '\n';
}
output:
std::atoi("42") is 42
std::atoi("3.14159") is 3
std::atoi("31337 with words") is 31337
std::atoi("words and 2") is 0
c++语言转换形式:
在http://en.cppreference.com/上给出了如下实例代码:
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
output:
std::stoi("45") is 45
std::stoi("3.14159") is 3
std::stoi("31337 with words") is 31337
参考:http://blog.csdn.net/caroline_wendy/article/details/29390573
http://en.cppreference.com/w/cpp/string/basic_string/to_string
http://en.cppreference.com/w/cpp/string/byte/atoi
http://en.cppreference.com/w/cpp/string/basic_string/stol