在C或C++编程中,何时应该使用单引号和双引号?
单引号表示一个字符,双引号表示一个字符串。
在Java中也是如此。
使用单引号用于单个字符,例如:
char ch = 'a';
这里的'a'
是一个字符常量,等于字符a的ASCII
值。
字符串使用双引号表示:
char str[] = "foo";
这里的"foo"
是一个字符串字面量。
使用"a"
是可以的,但是使用'foo'
是不可以的。
虽然我确定这并不回答原问者的问题,但是如果你像我一样在查找整数字面量中的单引号,C++14增加了在数字字面量中间添加单引号('
)的能力,以便为数字添加一些视觉分组。
constexpr int oneBillion = 1'000'000'000;
constexpr int binary = 0b1010'0101;
constexpr int hex = 0x12'34'5678;
constexpr double pi = 3.1415926535'8979323846'2643383279'5028841971'6939937510;
声明字符/字符串的不同方式
char char_simple = 'a'; // bytes 1 : -128 to 127 or 0 to 255
signed char char_signed = 'a'; // bytes 1: -128 to 127
unsigned char char_u = 'a'; // bytes 2: 0 to 255
// double quote is for string.
char string_simple[] = "myString";
char string_simple_2[] = {'m', 'S', 't', 'r', 'i', 'n', 'g'};
char string_fixed_size[8] = "myString";
char *string_pointer = "myString";
char string_poionter_2 = *"myString";
printf("char = %ld\n", sizeof(char_simple));
printf("char_signed = %ld\n", sizeof(char_signed));
printf("char_u = %ld\n", sizeof(char_u));
printf("string_simple[] = %ld\n", sizeof(string_simple));
printf("string_simple_2[] = %ld\n", sizeof(string_simple_2));
printf("string_fixed_size[8] = %ld\n", sizeof(string_fixed_size));
printf("*string_pointer = %ld\n", sizeof(string_pointer));
printf("string_poionter_2 = %ld\n", sizeof(string_poionter_2));
cout<<int('1')<<endl<<int(1);
string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string