反正常常用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"