c++ 字符串与数字的互相转化(二)

    科技2024-03-24  91

    字符串转数字:sscanf函数(将字符数组转为数字)

    char s[10]="123"; int a; sscanf(s,"%d",&a); printf("%d\n",a); //123 char s1[10]="12.3"; double b; sscanf(s1,"%lf",&b); printf("%.1lf\n",b); //12.3 string str="123"; int c; sscanf(str.c_str(),"%d",&c); printf("%d\n",c); //123

    数字转字符串:sprintf函数(数字转为字符数组)

    int a=123; char s[10]; sprintf(s,"%d",a); printf("%s",s); //123 double b=123.45; char s1[10]; sprintf(s1,"%.2lf",b); printf("%s",s1); //123.45 //string str=string(s1);

    字符串转数字:stoi()

    string s="1234"; int a=stoi(s);

    数字转字符串:to_string()

    int a=1234; string s=to_string(a);
    Processed: 0.024, SQL: 8