• (转载)字符串和数字相互转换


    本文转载自https://www.cnblogs.com/houchen/p/8984164.html

    一、利用 sprintf()函数和sscanf()函数

      (1)sprintf() 用于将数字转化为字符串

    #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() 用于将字符串转化为数字

    #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;
    }

  • 相关阅读:
    洛谷 P6295
    洛谷 P4240
    洛谷 P3287
    My rating is 1064.
    洛谷 P5071
    C语言 #include <> 与 #include “” 区别
    C语言 #pragma once
    C语言 typedef 和 define 区别
    C语言 define 定义函数(多行书写)
    C语言 define 定义函数
  • 原文地址:https://www.cnblogs.com/wenhao-Web/p/12167128.html
Copyright © 2020-2023  润新知