(atoi,atol,atof)&&c_str()
atoi: char* → int
atol: char* → long
atof: char* → double
注意要用c_str将string转化成c语言中的char*类型
stringstream
具体来说就是C++标准库中的
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
/************************************************************************/
/* 使用stringstream对象简化类型转换 */
/*C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能, */
/*即单纯性、类型安全和可扩展性。在本文中,我将展示怎样使用这些库来实现 */
/*安全和自动的类型转换。 */
/*如果你打算在多次转换中使用同一个stringstream对象, */
/*记住再每次转换前要使用clear()方法; */
/************************************************************************/
int _tmain(int argc, _TCHAR* argv[])
{
//stringstream通常是用来做数据转换的。
//1.int 与 string的转换
std::stringstream m_sstream;
std::string result;
int i=1000;
m_sstream<<i;
m_sstream>>result;
std::cout<<result<<"\n";
//2.int 与 char[]的转换
m_sstream.clear();
char res[8];
m_sstream<<8888;
m_sstream>>res;
std::cout<<res<<"\n";
//3.string 与 int的转换(并且可以按照空格进行读取)
m_sstream.clear();
int first,second;
m_sstream<<"666";
m_sstream>>first;
std::cout<<first<<std::endl;
//4.bool 与 int的转换
m_sstream.clear();
m_sstream<<true;
m_sstream>>second;
std::cout<<second<<std::endl;
return 0;
}