-
Notifications
You must be signed in to change notification settings - Fork 0
/
a trap of string.html
105 lines (84 loc) · 2.16 KB
/
a trap of string.html
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<!--
<link rel="Stylesheet" type="text/css" href="style.css">
-->
<link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen" />
<link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<title>a trap of string</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<header>
<div class="inner">
<h1>Wiki</h1>
<h2>by chenokay</h2>
<a href="https://github.com/chenokay" class="button"><small>View my project on</small>GitHub</a>
</div>
</header>
<div id="content-wrapper">
<div class="inner clearfix">
<section id="main-content">
<h1 id="toc_1">A trap of string</h1>
<pre>
#include <stdio.h>
#include <string>
enum T {
ELE1 = 0,
ELE2
};
int main()
{
std::string a;
a = ELE1;
std::string b = "hello";
b.append(a);
b.append("world");
printf("pint:%s\n", b.c_str());
return 0;
}
</pre>
<p>
这段代码会输出多少呢?
</p>
<p>
"helloworld" ?
</p>
<p>
不是的,实际的结果是hello,因为在a的初始化赋值中,ELE1被当做char类型进行构造,得到一个
</p>
<p>
长度为1,值为0的string,导致在a append到b后,再append的内容都被a的0字符截断而
</p>
<p>
没有打印出来。
</p>
<p>
实际上,在append操作中,是根据length长度来进行的,只要生成一个包括'\0'的string进行append
</p>
<p>
都会导致后续的append不能打印。
</p>
<p>
当然,若string a = "\0"; 是没有问题的,所以要分清string中'\0'字符和字符串的结尾'\0';
</p>
<p>
稍大意就造成问题。
</p>
</section>
<aside id="sidebar">
<h2>Zhen Chen</h2>
<p><a href="http://map.baidu.com/?newmap=1&ie=utf-8&s=s%26wd%3D%E5%A4%9A%E7%9B%9F">No.15 Wanquanzhuang Road, Haidian District, Beijing, China</a></p>
<p>chenokay@gmail.com</p>
</aside>
</div>
</div>
</body>
</html>