C++ 字串,字元數組,數字之間轉換

來源:互聯網
上載者:User

小的東西往往很麻煩,就是想利用圖片索引累加的方法儲存圖片。貼出一小段代碼

//圖片索引號int ImageIndex=0;int main(){   .......               //數字轉換為字串            ImageIndex++;            string Index;            char index[10];            sprintf_s(index,"%d",ImageIndex);            Index=index;            string ImageFile="D:\\test"+Index +".jpg";            cvSaveImage(&ImageFile[0],&storeImage);   .......}

將數字轉換為字串有兩種方法:一種用string下的字元流;一種是C下的sprintf, sscanf方法;

方法一:

用C++的streanstream:

#include <sstream>
#Include <string>
string num2str(double i)
{
        stringstream ss;
        ss<<i;
        return ss.str();
}

字串轉數字:

int str2num(string s)
 {   
        int num;
        stringstream ss(s);
        ss>>num;
        return num;
}

 方法二:

C library中的sprintf, sscanf 相對更快

可以用sprintf函數將數字輸出到一個字元緩衝區中. 從而進行了轉換...
例如:
已知從0點開始的秒數(seconds) ,計算出字串"H:M:S",  其中H是小時, M=分鐘,S=秒

         int H, M, S;
        string time_str;
        H=seconds/3600;
        M=(seconds%3600)/60;
        S=(seconds%3600)%60;
        char ctime[10];
        sprintf(ctime, "%d:%d:%d", H, M, S);             // 將整數轉換成字串
        time_str=ctime;                                                 // 結果 

與sprintf對應的是sscanf函數, 可以將字串轉換成數字

    char    str[] = "15.455";
    int     i;
    float     fp;
    sscanf( str, "%d", &i );         // 將字串轉換成整數   i = 15
    sscanf( str, "%f", &fp );      // 將字串轉換成浮點數 fp = 15.455000
    //列印
    printf( "Integer: = %d ",  i+1 );
    printf( "Real: = %f ",  fp+1 ); 
    return 0;最後cvSaveImage方法的第一個參數是char *類型的,字串轉換為字元數組的方法char *bb=&ImageFile[0];

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.