关于c++:C与QT的sprintf的用法

33次阅读

共计 749 个字符,预计需要花费 2 分钟才能阅读完成。

反正常常用 sprintf 这个函数,因为太好用了吧。

通过这个,能够拼字符串,包含各种类型的变量,都能够组装到外面,拼字符串是程序最常常的一个操作了,能够说,很多程序就是组装字符串的过程,记得一个同学以前说过:程序的实质不就是解决数据吗?是啊,就是这点事。

用法是统一的,如下:

C 库函数 int sprintf(char str, const char format, …) 发送格式化输入到 str 所指向的字符串
这就是他们独特的中央,不同的就是 QT 通过面向对象封装了一下,如此而已​。

上面总结了在 C ++ 与 QT 当中这种函数的用法,很简略,两者比照着记,印象更深一些吧:

void MainWindow::on_pushButton_3_clicked()
{
    //1、c++ 的字符串格式化
    char a[12] = "this is c";
    char b[64] = {0};
    sprintf(b, "function %s", a);
    qDebug()<<b;

    //2、QT 的字符串格式化
    QString info = "this is a test";
    //1.1/QT 的第一种用法,实例调用法:QString test;
    test.sprintf("function:%s", info.toStdString().c_str());
    qDebug()<<info;
    qDebug()<<test;
    //1.2/QT 的第二种用法,动态调用法:QString info2 = QString::asprintf("function:%s", info.toStdString().c_str());
    qDebug()<< info2;}

输入状况如下:

function this is c  
"this is a test"
"function:this is a test"
"function:this is a test"

正文完
 0