C++笔记-使用sprintf把各个类型转成char*(long long, doule,int)

    xiaoxiao2025-09-11  68

    目录

     

     

    背景

    演示及代码


     

    背景

    在某些时候,不能使用其他的框架,只能使用标准的东西,进行操作,这此记录下,方便以后快速敲代码。

    这个sprintf在stdio.h的头文件中。

    本次有以下类型转成char*

    int

    long

    long long

    double

    unsigned int

    string

     

    演示及代码

    程序运行截图如下:

    源码如下:

    #include <stdio.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { long long longData = 1234567890123456; int intData = 255; unsigned int uintData = 0x11111111; string strData = "aaabbbcccddd12345"; float floatData = 100.001; double doubleData = 100.000011; char charPData[64]; sprintf(charPData, "%lld", longData); cout << "long long to char* : " << charPData << endl; sprintf(charPData, "%d", intData); cout << "int to char* : " << charPData << endl; sprintf(charPData, "%u", uintData); cout << "uint to char* : " << charPData << endl; cout << "string to char* : " << strData.c_str() << endl; sprintf(charPData, "%f", floatData); cout << "float to char* : " << charPData << endl; sprintf(charPData, "%lf", doubleData); cout << "double to char* : " << charPData << endl; cout << "--------------" << endl; sprintf(charPData, "Hello %lf", doubleData); cout << "in the end : " << charPData << endl; return 0; }

     

    最新回复(0)