Show toolbar

2013年7月8日 星期一

String conversion

標題:C/C++字串轉換
VC++ (main.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream> //ostringstream
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Character Sequences
//char c[13] = "CharVariable";
char c[13] = {'C', 'h', 'a', 'r', 'V', 'a', 'r', 'i', 'a', 'b', 'l', 'e', '\0'};
//Pointer
char *p = "Pointer";
//Class
string s = "String";
//String to Char
strcpy(c, s.c_str());
cout << c << endl;
//Char to String
s.assign(c);
cout << s << endl;
//Pointer to Char
strcpy(c, p);
cout << c << endl;
//Char to Pointer
p = &c[0];
cout << p << endl;
//String to Float
float num1 = 0.0f;
s = "233.42";
num1 = atof(s.c_str());
cout << num1 << endl;
//Float to String
float num2 = 233.42f;
ostringstream buffer;
buffer << num2;
s = buffer.str();
cout << s << endl;
return 0;
}
說明:
字元陣列、指標字串、VC字串,互相轉換。

沒有留言:

張貼留言