史上最全資料型別轉換(Qt\C++\C)
阿新 • • 發佈:2021-06-20
1 #include <QCoreApplication> 2 3 #include <iostream> 4 using namespace std; 5 6 QString qstr1 = "qyanjiachen"; 7 QString qstr2 = "1234"; 8 9 10 11 std::string str1 = "yanjiachen"; 12 std::string str2 = "1234"; 13 14 15 int int1 = 1234; 16 int int2 = 0x123;17 18 19 char ch1 = 'a'; 20 char ch2[] = "abcd"; 21 22 23 24 int main(int argc, char *argv[]) 25 { 26 QCoreApplication a(argc, argv); 27 printf("%s",str1.c_str()); //printf後的字串要求為物件的首地址 28 //取一個數字的高8位和低8位 29 int value = 515; 30 int mainVersion = (value & 0xFFFF) >> 8; 31 int minorVersion = value & 0xFF; 32 cout<<mainVersion; 33 34 //QString轉String 35 QString qstr6; 36 string str12 = qstr6.toStdString(); 37 38 //String轉QString 39 string str11; 40 QString qstr7 = QString::fromStdString(str11); 41 42 //QString轉char*--------方法一,使用string43 QString qstr1 = "qyanjiachen"; 44 std:string str=qstr1.toStdString(); 45 const char* ch=str.c_str(); 46 47 //string轉char*,包含3中方法:1,2,3 48 string str0 = "hello worls"; 49 const char *p = str.data();//1 50 const char *p2 =str.c_str();//2:若不加 const,編譯時會報錯:無法從 "const char*" 轉換為 "char*"; 51 char buf[50]; 52 str.copy(buf,5,0); 53 *(buf+5)='\0';//需要手動加結束符 54 55 //QString轉char*--------方法二,使用QByteArray 56 QString qstr2; 57 QByteArray ba=qstr2.toLatin1(); 58 char *cstr=ba.data(); 59 60 //char*轉QString 61 char *ch1="mmm"; 62 QString qstr = QString(QLatin1String(ch1)); 63 64 //char*轉string,可直接賦值 65 char *p1="hello"; 66 string str1=p; 67 68 //string轉char[],區別就是結尾差一個'\0' 69 string str2="hello"; 70 char ch3[10]; 71 int i=0; 72 for(i=0;i<str2.size();++i) 73 { 74 ch3[i]=str2[i]; 75 } 76 ch3[i]='\0'; 77 78 //char[]轉string 79 char ch4[60]="hello"; 80 string str5=ch4; 81 82 //char轉string,有三種方法 83 char ch7 ='l';//1 84 string str7(1,ch7);//2, 85 string str8; 86 str8.push_back(ch7); 87 88 89 //int 轉QString,double轉QString 90 int int1 = 1234; 91 double dou=63.23; 92 QString qstr5=QString("%1").arg("%1").arg(dou); 93 94 QString qstr3=QString::number(int1);//(int1,16)表示換算成16進位制 95 96 //QString 轉int,轉double 97 QString qstr4="1234"; 98 int j=qstr4.toInt(); 99 double dou2=qstr4.toDouble(); 100 101 //Char與QChar互轉 102 QChar qch1='v'; 103 char ch6=qch1.toLatin1(); 104 qch1=QChar(ch6); 105 106 //char*轉char 107 char *ss="abcdefghijklmn"; 108 char ch9[100]; 109 strcpy(ch9,ss); 110 111 //char轉char* 112 char ch8[]="abcdefghijklmn"; 113 char *s = ch8; 114 115 //QByteArray轉char* 116 char * ch10 ="aaaaaaaasds"; 117 QByteArray ba2; 118 ch10 = ba.data(); 119 120 //char*轉QByteArray 121 char *ch11; 122 QByteArray ba3 = QByteArray(ch11); 123 124 //int轉string 125 int m=9; 126 string str15 = "" + m; 127 128 //string轉int 129 int k= atoi(str.c_str());//stof(floa)),atol(轉long) 130 return a.exec(); 131 }