(轉載)字符串和數字相互轉換

本文轉載自https://www.cnblogs.com/houchen/p/8984164.html

1、利用 sprintf()函數和sscanf()函數

  (1)sprintf() 用於將數字轉化爲字符串html

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char str[10]; 
    int a=1234321;

    //將整數轉化爲字符串
    sprintf(str,"%d",a);
    int len=strlen(str);
    cout<<"字符串"<<str<<endl;
    cout<<"長度"<<len<<endl;

    char str1[10]; 
    double b=123.321;

    //將浮點數轉化爲字符串
    sprintf(str1,"%.3lf",b);
    int len1=strlen(str1);
    cout<<"字符串"<<str1<<endl;
    cout<<"長度"<<len1<<endl;
    return 0;
}

 

  (2)sscanf() 用於將字符串轉化爲數字ios

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char str[]="1234321"; 
    int a; 
    sscanf(str,"%d",&a); 
    cout<<a<<endl;

    char str1[]="123.321"; 
    double b; 
    sscanf(str1,"%lf",&b); 
    cout<<b<<endl;
    return 0;
}

相關文章
相關標籤/搜索