String与其他基本类型的转换

最近老是遇到string和其他基本类型的转换要求,于是就抽空来写点博客。C++中,string应该就是个人为做出来的类型,它具有良好的封装性,但是,有些时候,它确实不如python中的操作来的方便快捷。不过,有很多前辈也早就写好了代码供我们使用。

C++11起,std::to_string()便加入C++标准,其重载函数列表为:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

这样我们便可以轻松自如的将其他基本类型转换为string,目标也就完成了一半。

从参考中得知,C++11标准库定义了三种类型字符串流:istringstream,ostringstream,stringstream。

这三种字符串流被包含在sstream头文件中。

Class istringstream:

istringstream::istringstream(string str,ios_base::openmode which = ios_base::in);  //Constructor
istringstream::istringstream(ios_base::openmode which = ios_base::in);        //Default Constructor
string istringstream::str() const;
//returns a string object with a copy of the current contents of the stream.
void istringstream::str(const string& str);
//sets str as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence.
void istringstream::swap(istringstream &X);
//Exchanges all internal data between x and *this.
//其中,该类重载了>>运算符,自动将数据转换为其匹配类型后输出。
istringstream S("15.99 test");
string tmp;
double test = 12.90;
S>>test;        //此时,test的值为15.99
S>>tmp;         //此时,tmp的值为"test"
//我认为,istringstream的本质是数据流,记住这一点,很多操作将非常清晰
/*
不过,我有一点疑惑,即下面的代码为何如此:
Code:
#include 
#include 
using namespace std;

int main()
{
    istringstream two("16.77");
    double test2,test1;
    two>>test1;
    two.str("18.99");
    cout<>test2;
    cout<

Class ostringstream:

ostringstream::ostringstream(string str,ios_base::openmode which = ios_base::out);  //Constructor
ostringstream::ostringstream((ios_base::openmode which = ios_base::out);           //Default Constructor
//同样的,ostringstream也有str(),swap()函数
//类似的,该类支持重载了<<运算符,允许将任何基本类型插入保存至ostrigstream对象中

Class stringstream:

//该类其实继承了上面两个类,重载了>>,<<运算符,支持向流中输入数据,并根据代码,自动输出数据转换为合适类型。
Demo:
stringstream tmp;
string t ="17.66";
tmp<double tt;
tmp>>tt;            //此时,tt的值为17.66

PS:最近被C++的文件输入输出流,以及stdout、stdin、stderr搞的头大,周末好好看看别人的博客学习学习。

(资料来源于The C++ Resources Network:www.cplusplus.com)

你可能感兴趣的:(C/C++)