01static_cast
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s = "test";
string s2;
int i, i2;
for ( i = 0; i < 80; i++)
{
char char_i = {0};
string s3 = {0};
i2 = i;
char_i = static_cast<char>(i2) + '0';
s2 = char_i;
s3 = s + s2;
cout<< s3 <<endl;
}
cout<< s <<endl;
return 0;
}
/*
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
test:
test;
test<
test=
test>
test?
test@
testA
testB
testC
testD
testE
testF
testG
testH
testI
testJ
testK
testL
testM
testN
testO
testP
testQ
testR
testS
testT
testU
testV
testW
testX
testY
testZ
test[
test\
test]
test^
test_
test`
testa
testb
testc
testd
teste
testf
testg
testh
testi
testj
testk
testl
testm
testn
testo
testp
testq
testr
tests
testt
testu
testv
testw
testx
testy
testz
test{
test|
test}
test~
test
test
*/
02
#include <iostream>
#include <sstream>
// 使用字符串流进行添加
using namespace std;
int main()
{
int i = 0;
string s1 = "this is test ";
string s3;
string s2;
for ( i = 0; i < 10; i++)
{
stringstream ss; //一定要初始化不然就会变成0 01 012
ss << i;
s2 = ss.str();
s3 = s1 + s2; // 不要写成string s3 = s1 + s2
//因为命名空间的存在 会导致 这里的 s3与外面的s3不是同一个东西
cout << s3 << endl;
}
cout << s3 << endl;
return 0;
}
/*
this is test 0
this is test 1
this is test 2
this is test 3
this is test 4
this is test 5
this is test 6
this is test 7
this is test 8
this is test 9
this is test 9
*/
03my_to_string
#include<iostream>
#include<string>
using namespace std;
#define max 100
string my_to_string(const int n)
{
int m = n;
char s[max];
char ss[max];
int i=0,j=0;
if (n < 0)// 处理负数
{
m = 0 - m;
j = 1;
ss[0] = '-';
}
while (m>0)
{
s[i++] = m % 10 + '0';
m /= 10;
}
s[i] = '\0';
i = i - 1;
while (i >= 0)
{
ss[j++] = s[i--];
}
ss[j] = '\0';
return ss;
}
int main()
{
char test_arr[50] = {"this is test char_arr to string"};
string s1 = test_arr;
cout << s1 << endl;
string s;
int m = 2;
while(1)
{
m = m*m;
//在my_to_string 中定义大小为100的数组
s = my_to_string(m) + "this is test int add string";
cout << s << endl;
if( m >= 10000)
{
break;
}
}
return 0;
}
/*
this is test char_arr to string
4this is test int add string
16this is test int add string
256this is test int add string
65536this is test int add string
65536 * 65536 = int 最大值 4,294,967,296-1
*/
04 库 to_string
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926348);
std::string perfect = std::to_string(1+2+4+7+14*2) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
/*
pi is 3.141593
42 is a perfect number
*/