string 转 int, int 转 string

int 转 string

#include <string>
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
        //第一种方式, 利用string库函数
	string pi = "pi is " + to_string(3.1415926);
	cout << pi << endl;

        //第二种方式, 利用字符串输出流
	std::ostringstream str;
	int i = 2012;
	str << i;
	cout << str.str() << endl;
}

 

string转int

#include <string>
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
        //第一种方式,利用string库函数
	string str = "123456";
	int i = stoi(str);
        //第二种方式, 利用c库函数
	int j = atoi(str.c_str());
        //利用输入流
	istringstream is("123456");
	int k;
	is >> k;
	cout << i << '\t' << j << '\t' << k << '\t';
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/qq_29869043/article/details/82527431
今日推荐