zoukankan      html  css  js  c++  java
  • C++中string和int的转换

    做ACM时,经常用到string和int的转换,下面的程序:

    #include<iostream>
    #include<string>
    #include<sstream>
    
    
    using namespace std;
    
    int main()
    {
        ///////////////////////////   string 转为 int
        string str="1234";
        int n;
        istringstream iss;//istringstream从string读入,和cin一样仅仅重载了>>,可以把string转为int
        iss.clear();//每次使用前先清空
        iss.str(str);
        iss>>n;//将输入流中的内容写入到int n,
        cout<<n<<endl;
    
        ////////////////////////////////   int 转为 string
    
        n=111;
        ostringstream oss;//用于向string写入,和cout<<一样,仅仅重载了<<
        oss<<n;
        str=oss.str();
        cout<<str<<endl;
    
    
        /////////////////////////////////  string 转为  int
        str="22222";
        sscanf(str.c_str(),"%d",&n);  //scanf前面加s用于把str输入到n中
        cout<<n<<endl;
    
    
        ///////////////////////////////   int 转为 string
    
    
        int   ss=1000;
        char   temp[64];
        sprintf(temp,"%d",ss); //printf前面加s用于将ss按整数形式输出到数组temp中,不能直接给str.c_str();
        str=temp;//再把数组temp赋值给str;
        cout<<str<<endl;
        return 0;
    }
  • 相关阅读:
    2019.9.25 初级数据结构——树状数组
    2019.9.29 陪审团
    2019.9.27 硬币
    0070-星星阵
    0069-简单的回文数问题
    0068-简单的求和问题
    0067-水仙花数
    0066-若干个数求和问题
    0065-数方块
    0064-简单的平方和
  • 原文地址:https://www.cnblogs.com/wang7/p/2454470.html
Copyright © 2011-2022 走看看