zoukankan      html  css  js  c++  java
  • 使用sstream来进行类型转换

    在某种情况下,我们不得不进行整型等数据类型与字符串类型的转换,比如,将“1234”转换为整数,常规的我们可以使用atoi函数来进行转换,或者是写一个循环来做转换,我们在这里也可以使用sstream类来做转换。示例代码如下,演示了atoi和sstream的方法。

    #include<stdio.h>
    #include<iostream>
    #include<sstream>
    #include<stdlib.h>
    using namespace std;
    int main(){
    	stringstream ss;
    	//将整型转换为string
    	int i=100;
    	ss<<i;
    	string str="";
    	ss>>str; 
    	cout<<"str:"<<str<<endl;
    	//反过来将string转换为int
    	ss.clear();//注意清除一下,不然下面的操作 会受到上面的影响。 
    	int j;
    	ss<<str;
    	ss>>j;
    	cout<<"j:"<<j<<endl; 
    	//使用atoi函数来进行转换。
    	cout<<"atoi(str):"<<atoi(str.c_str())<<endl; 
    	return 0;
    }
    

      

  • 相关阅读:
    CSS
    html5
    XHTML
    HTML
    git 教程 --git revert 命令
    Git 教程 --git merge 命令
    git 教程 --git reset 命令
    git 教程 --git cherry-pick 命令
    git 教程 --git stash命令
    git 教程 --git diff功能
  • 原文地址:https://www.cnblogs.com/JsonZhangAA/p/8506081.html
Copyright © 2011-2022 走看看