[英]String initialization with double quotes
I'm doing some tutorial, and had this line 我正在做一些教程,并有这条线
const std::string spaces(greeting.size(), " ");
However that didn't work until i changed double quotes to single quotes like 但是,直到我将双引号更改为单引号后,这种方法才起作用
const std::string spaces(greeting.size(), ' ');
What is the point about quotes in string initialization? 字符串初始化中的引号有什么意义? I've tried to check http://www.cplusplus.com/reference/string/string/ , but didn't find something that would explain this to me
我尝试检查http://www.cplusplus.com/reference/string/string/ ,但是没有找到可以向我解释的内容
Double-quoted " "
is string literal in C++ (represented by const char [N]
), while single-quoted ' '
is a character literal ( char
), so you were calling (std::size_t, const char [N])
constructor. 双引号
" "
是C ++中的字符串文字(用const char [N]
),而单引号' '
是字符文字( char
),因此您正在调用(std::size_t, const char [N])
构造函数。
It doesn't exist, so you get a compilation error. 它不存在,因此会出现编译错误。
You need to change it to one of the available constructors like: 您需要将其更改为可用的构造函数之一,例如:
string (size_t n, char c);
string (const char* s);
(which you already did by changing second parameter to ' '
) (您已经通过将第二个参数更改为
' '
)
That's because you're using this constructor: string (size_t n, char c)
(no. 6 in the reference you linked), which fills the newly constructed string with n
chars c
. 这是因为您正在使用此构造函数:
string (size_t n, char c)
(链接的引用中的编号6),该构造函数使用n
chars c
填充了新构造的字符串。 If you use double quotes you create a string literal, single quotes mean chars. 如果使用双引号创建字符串文字,则单引号表示字符。
There are character literals and string literals in C++. C ++中有字符文字和字符串文字。
For example a character enclosed in single quotes like 'A' denotes a character literal and represents one character and has type char
. 例如,用单引号括起来的字符,例如'A'表示字符文字,表示一个字符,类型为
char
。
If you will enclose symbol A in double quotes like "A"
then you get a string literal that has type cont char[2]
and has internal representation like 如果将符号A括在双引号中,例如
"A"
则将得到一个字符串常量,其字符串类型为cont char[2]
,内部表示形式如
{ 'A', '\0' }
that is it consists from two characters including the terminating zero. 即它由两个字符组成,包括终止的零。
You can see the difference running this simple porgram 您可以看到运行此简单porgram的区别
#includde <iostream>
int main()
{
std::cout << "sizeof( 'A' ) = " << sizeof( 'A' ) << std::endl;
std::cout << "sizeof( \"A\" ) = " << sizeof( "A" ) << std::endl;
}
Class std::basic_string (or std::string) has the following constructor 类std :: basic_string(或std :: string)具有以下构造函数
basic_string(size_type n, charT c, const Allocator& a = Allocator());
and in this declaration 在这份宣言中
const std::string spaces(greeting.size(), ' ');
this constructor is used. 使用此构造函数。 It initializes the string with the greeting.size() number of space character.
它使用空格字符的greeting.size()初始化字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.