stringstream流来操作数字与字符串的操作

对于C++中的字符串与数字的转化是可以通过流来转化的;
上代码!!!

#include
#include 
#include
#include  


using namespace std;

int main()
{
    int p = 12351;
    cout << "p =" << p << endl;
    cout << endl;
    string oo;
    stringstream ss;
    ss << p;
    ss >> oo;
    for (int i = 0; i < ss.str().size(); i++)
    {
        cout << ss.str().at(i) << endl;
    }
    cout << endl;
    for (int i = 0; i < oo.size(); i++)
    {
        cout << oo.at(i) << endl;
    }
    cout << endl;


    system("pause");

}
image.png

string转化为num同理;注意头文件

#include
#include 
#include
#include  


using namespace std;

int main()
{
    int p = 12351;
    cout << "p =" << p << endl;
    string oo;
        //定义两个流的副本
    stringstream ss;
    stringstream ss1; 
    ss << p;//将p输入ss流
    ss >> oo;//将ss流用string的格式输出给oo
    reverse(oo.begin(), oo.end()); //algorithm算法,翻转string
        //输出ss的流的副本
    for (int i = 0; i < ss.str().size(); i++)
    {
        cout << ss.str().at(i) << endl;
    }
    for (int i = 0; i < oo.size(); i++)
    {
        cout << oo.at(i) << endl;
    }
    ss1 << oo;
    for (int i = 0; i < ss1.str().size(); i++)
    {
        cout << ss1.str().at(i) << endl;
    }
    ss1 >> p;
    cout << "p =" << p << endl;

    system("pause");

}
image.png

可能有人会奇怪为什么需要两个流呢?那我们来试试只有一个流的时候

#include
#include 
#include
#include  


using namespace std;

int main()
{
    int p = 12351;
    cout << "p =" << p << endl;
    cout << endl;
    string oo;
    stringstream ss;
    ss << p;
    ss >> oo;
    reverse(oo.begin(), oo.end());
    for (int i = 0; i < ss.str().size(); i++)
    {
        cout << ss.str().at(i) << endl;
    }
    cout << endl;
    for (int i = 0; i < oo.size(); i++)
    {
        cout << oo.at(i) << endl;
    }
    cout << endl;

    ss << oo;
    for (int i = 0; i < ss.str().size(); i++)
    {
        cout << ss.str().at(i) << endl;
    }
    cout << endl;
    ss >> p;
    cout << "p =" << p << endl;

    system("pause");

}
image.png

第二次的流的输入并没有改变流ss的值。

你可能感兴趣的:(stringstream流来操作数字与字符串的操作)