C++中3種方式把字串和數字連線起來
阿新 • • 發佈:2019-02-07
以前老用Java裡面的String類,用過的人都知道好舒服,連線字串和數字只需要用一個 + 號就可以了。在這裡真的想把C++中string類+號功能加強一下。希望有能力的人可以做一下,不然總是感覺string類缺點啥呢(每次都和java比 O(∩_∩)O哈哈~)
不廢話了,如題直接晒程式碼
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
//第一種C風格的轉化(以前一直喜歡的 sprintf 功能強大)
void test()
{
char *s = "dong";
int a = 52;
float b = .1314;
char *buf = new char[strlen(s) + sizeof(a) + 1];
sprintf(buf, "%s%d%.4f", s, a, b);
printf("%s\n", buf);
}
//半C半C++風格
void test1()
{
string s = "dong";
int a = 520;
char *buf = new char[10];//2147483647 int最大值
_itoa(a, buf, 10); //itoa雖然可以轉化為各種進位制,但是注意不能是float或者double
s += buf;
cout << s << "\t";
_itoa(a, buf, 16);
s += buf;
cout << s << endl;
}
//純C++風格
void test2()
{
string s = "陳明東";
int a = 520;
double b = .1314;
ostringstream oss;
oss << s << a << b << endl;
cout << oss.str() << endl;
}
int main()
{
test();
test1();
test2();
return 0;
}
/*
dong520.1314
dong520 dong520208
陳明東5200.1314
*/