2017年11月23日 星期四

程式設計I -- 變數型別的轉換

1.  int to string 整數轉字串
#include<iostream>
#include<string>
using namespace std;
int main()
{
int v = 200;
string s = to_string(v);
cout << s << endl;
return 0;
}

2. string to int 字串轉整數
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s = "100";
int v = stoi(s);
v++;
cout << v << endl;
return 0;
}

stod – 字串轉 double
stof – 字串轉 float
stol –  字串轉長整數 (long 也是種型別,是整數,可以容納比 int 更多的數字範圍)
stoull – 字串轉無正負號長長整數 (unsigned long long)

3. string to char 字串轉字元陣列
#include<iostream>
#include <string.h>

using namespace std;
int main(){
string test_string="test_string";
char result_char[20];
strcpy(result_char, test_string.c_str());
for(int i = 0;i < test_string.size();i++)
{
cout << result_char[i] << " ";
}
}
//output : t e s t _ s t r i n g

4. char to string 字元陣列轉字串
#include<iostream>
#include <string.h>

using namespace std;
int main(){
char test_char[] = "test_char";
//方法一
string result_string1(test_char);
//方法二
string result_string2;
result_string2.assign(test_char);
cout<<"result_string1: "<<result_string1<<endl;
cout<<"result_string2: "<<result_string2<<endl;
}
//output
//result_string1: test_char
//result_string2: test_char

沒有留言:

張貼留言