01-C++数据类型

3、基础类型

3.1、简单变量

变量的命名

carDrip和cardRip

或boat_sport和boats_port

此外,还有有前缀的命名,使用前缀表示数据类型。常见的前缀有:str(表示字符串)、n(表示整数值)、b(表示布尔值)、p(表示指针)、c(表示单个字符)和m(表示一个类成员值)

nMyWeight

整型长度

C++提供了一种灵活的标准,它确保了最小长度

  • short至少16位
  • int至少与short一样长
  • long至少32位,且至少与int一样长
  • longlong至少64位,且至少与long一样长
#include <iostream>
#include <climits>		//包含整数的限制信息

int main() {
	using namespace std;
	short n_short = SHRT_MAX;
	int n_int = INT_MAX;
	long n_long = LONG_MAX;
	long long n_llong = LLONG_MAX;

	//sizeof operator yields size of type or of variable
	cout << "short is " << sizeof n_short << " bytes." << endl;
	cout << "int is " << sizeof(int) << " bytes." << endl;
	cout << "long is " << sizeof n_long << " bytes." << endl;
	cout << "long long is " << sizeof n_llong << " bytes." << endl << endl;

	cout << "Maxinum values:" << endl;
	cout << "short: " << n_short << endl;
	cout << "int: " << n_int << endl;
	cout << "long: " << n_long << endl;
	cout << "long long: " << n_llong << endl << endl;

	cout << "Minnum int value=" << INT_MIN << endl;
	cout << "Bits per byte =" << CHAR_BIT << endl;		//字节的位数
	return 0;
}
/*
short:2
int:4
long:4
long:8
*/

对于整数类型的限制,使用头文件climits(在老式中为limits.h)。即最大值、最小值等常量

在这里插入图片描述

对于int、long、long long

初始化

int owls=100;		//传统C语言初始化,
int wrens(432);		//可供选择的C++初始化

在C++98和C++11中,可以使用大括号对单值进行初始化

在C++98中,将大括号用于单值变量的情形还不多,但是对于C++11标准就多很多了。采用这种方式时,可以使用=,也可以不用
int emus{7};
int rheas={12};

其次,大括号内可以不包括任何东西。在这种情况下,变量将被初始化为0.
int rocs ={};
int phy{};

无符号类型

short的表示范围是-32768到+32768

unsigned short 表示的符号是0-65535

// exceed.cpp -- exceeding some integer limits
#include <iostream>
#define ZERO 0      // makes ZERO symbol for 0 value
#include <climits>  // defines INT_MAX as largest int value

int main() {
	using namespace std;
	short sam = SHRT_MAX;     // initialize a variable to max value
	unsigned short sue = sam;// okay if variable sam already defined

	cout << "Sam has " << sam << " dollars and Sue has " << sue;
	cout << " dollars deposited." << endl
	     << "Add $1 to each account." << endl << "Now ";

	sam = sam + 1;	//32767+1,溢出,-32768
	sue = sue + 1;
	cout << "Sam has " << sam << " dollars and Sue has " << sue;
	cout << " dollars deposited.\nPoor Sam!" << endl;

	sam = ZERO;
	sue = ZERO;		//0-1,溢出,65536
	cout << "Sam has " << sam << " dollars and Sue has " << sue;
	cout << " dollars deposited." << endl;
	cout << "Take $1 from each account." << endl << "Now ";

	sam = sam - 1;
	sue = sue - 1;
	cout << "Sam has " << sam << " dollars and Sue has " << sue;
	cout << " dollars deposited." << endl << "Lucky Sue!" << endl;
	// cin.get();
	return 0;
}

如果超越了限制,其值将为范围另一端的取值。C++确保了无符号类型类型的这种行为;但C++并不保证有符号整形超越限制(上溢出和下溢出)时不出错。

image-20230809164909524

如果知道变量表示的数值可能大于16位整数的最大值,则使用long。【因为在移植到别的操作系统中,int可能由32位变成16位】。

如果short比int小,则使用short可以节省内存。如果节省内存很重要,则应使用short而不是int,计时它们的长度是一样的。例如,假设要将程序从int是16位的系统移植到int是32位的系统,则用于存储int的数组的内存量将加倍,但是short的数组是不受影响的。

如果只需要一个字节,可使用char。

进制

有8进制、10进制、16进制,默认的是10进制

// hexoct1.cpp -- shows hex and octal literals
#include <iostream>

int main() {
	using namespace std;
	int chest = 42;     // decimal integer literal
	int waist = 0x42;   // hexadecimal integer literal
	int inseam = 042;   // octal integer literal

	cout << "Monsieur cuts a striking figure!\n";
	cout << "chest = " << chest << " (42 in decimal)\n";
	cout << "waist = " << waist << " (0x42 in hex)\n";
	cout << "inseam = " << inseam << " (042 in octal)\n";
	// cin.get();
	return 0;
}

对于C++,如果要以16进制或8进制方式显示值,则可以使用cout的一些特殊性。cout<<hex、cout<<oct

int main() {
	using namespace std;
	int chest = 42;
	int waist = 42;
	int inseam = 42;

	cout << "Monsieur cuts a striking figure!"  << endl;
	cout << "chest = " << chest << " (decimal for 42)" << endl;
	cout << hex;      // manipulator for changing number base
	cout << "waist = " << waist << " (hexadecimal for 42)" << endl;
	cout << oct;      // manipulator for changing number base
	cout << "inseam = " << inseam << " (octal for 42)" << endl;
	// cin.get();
	return 0;
}

标识符hex位于名称空间std中,而程序使用了该名称空间。

如果省略编译指令using,而使用std::cout、std::endl、std::hex、std::oct。

字符类型

char类型是专为存储字符(如数字和字母)而设计的。此外,char也可以看作是 比short更小的整形

输入时,cin将键盘输入的M转换为77;输出时,cout将值77转换为所显示的字符M。

// chartype.cpp -- the char type
#include <iostream>
int main( )
{
    using namespace std;
    char ch;        // declare a char variable

    cout << "Enter a character: " << endl;
    cin >> ch;
    cout << "Hola! ";
    cout << "Thank you for the " << ch << " character." << endl;
    // cin.get();
    // cin.get();
    return 0;
}

下面程序说明了这一单。cin和cout的行为都是由变量类型引导的。如果将77存储在int变量中,则cout将把它显示为77。字符使用单引号’M’,对于字符串使用双引号。

最后,引入cout的一项特性——cout.put()函数

#include <iostream>

int main() {
	using namespace std;
	char ch = 'M';       // assign ASCII code for M to ch
	int i = ch;          // store same code in an int
	cout << "The ASCII code for " << ch << " is " << i << endl;

	cout << "Add one to the character code:" << endl;
	ch = ch + 1;          // change character code in ch
	i = ch;               // save new character code in i
	cout << "The ASCII code for " << ch << " is " << i << endl;

	// using the cout.put() member function to display a char
	cout << "Displaying char ch using cout.put(ch): ";
	cout.put(ch);

	// using cout.put() to display a char constant
	cout.put('!');

	cout << endl << "Done" << endl;
	// cin.get();
	return 0;
}

/*
The ASCII code for M is 77
Add one to the character code:
The ASCII code for N is 78
Displaying char ch using cout.put(ch): N!
Done
*/

在Release2.0之后,C++将字符常量存储为char类型,而不是int类型。这意味着cout现在可以正确处理字符常量了。

在C++中,有一些转义字符,如下图所示。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bsfcFQ4A-1691999308835)(.\pics\8-9-7.png)]

// bondini.cpp -- using escape sequences
#include <iostream>
int main()
{
    using namespace std;
    cout << "\aOperation \"HyperHype\" is now activated!\n";
    cout << "Enter your agent code:________\b\b\b\b\b\b\b\b";
    long code;
    cin >> code;
    cout << "\aYou entered " << code << "...\n";
    cout << "\aCode verified! Proceed with Plan Z3!\n";
    // cin.get();
    // cin.get();
    return 0; 
}
/*
Operation "HyperHype" is now activated!
Enter your agent code:23456___
You entered 23456...
Code verified! Proceed with Plan Z3!
*/

新增的类型

char16_t和char32_t。底层时一种内置的整形

char16_t ch1=u'q';
char32_t ch2=U'\U0000222B';

bool类型

C++标准中添加了bool的新类型。

在计算中,布尔变量的值可以是true或false。C++将非零解释为true,将零解释为false。

bool is_ready = true;
//字面值true和false都可以通过提升转换为int类型,true被转换位1,而false被转换为0
int ans=true;
int promise=false;
//任何数字值或指针值都可以被隐式转换(即不用显式强制转换)为bool值。任何非零值都被转换位true,而零被转换为false
bool start =-100;
bool stop = 0;

3.2、const

创建常量的通用格式如下:

const type name =value;

const int val=10;

相较于#define语句,const有以下的好处

  • 它能够明确指定类型
  • 可以使用C++的作用域规则将定义限制在特定的函数或文件中
  • 可以将const用于更复杂的类型中,如数组和结构

3.3、浮点数

C++有两种浮点数的表示方法

3.3.1、表示方法

1、标准小数点表示法

12.34
0.000023
8.0
45678.2345678

2、E表示法

2.52e+8
8.33e-4
7E5

3.3.2、浮点类型

float至少32位;double至少48位,且不少于float;long double不少于double

通常,float为32位;double为64为;long double为80、96或128位

对于不同类型的浮点数,小数点后的精确度不同

// floatnum.cpp -- floating-point types
#include <iostream>

int main() {
	using namespace std;
	cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point
	float tub = 10.0 / 3.0;     // good to about 6 places
	double mint = 10.0 / 3.0;   // good to about 15 places
	const float million = 1.0e6;

	cout << "tub = " << tub;
	cout << ", a million tubs = " << million *tub;
	cout << ",\nand ten million tubs = ";
	cout << 10 * million *tub << endl;

	cout << "mint = " << mint << " and a million mints = ";
	cout << million *mint << endl;
	// cin.get();
	return 0;
}

3.3.3、浮点常量

如果希望常量为float类型,使用f或F后缀。如果时long double类型,可以使用l或L的后缀

1.234f
2.45E20F
2.456345E28		//double
2.2L			//long double

3.3.4、浮点数优缺点

两大优点

  • 它们可以表示整数之间的值
  • 由于有缩放因子,它们表示的范围大很多

另一方面,浮点运算的速度通常比整数运算慢,且精度将降低。

// fltadd.cpp -- precision problems with float
#include <iostream>

int main() {
	using namespace std;
	float a = 2.34E+22f;
	float b = a + 1.0f;

	cout << "a = " << a << endl;
	cout << "b - a = " << b - a << endl;
	// cin.get();
	return 0;
}

float仅能表示数字的前6位或前7位。

类型的分类

类型signed char、short、int和long统称为符号整型;它们的无符号版本统称为无符号整型。

C++11新增了long long、bool、char、wchar_t。

符号整数和无符号整型统称为整型。C++11新增了char16_t和char32_t。

float、double和long double统称为浮点型。整数和浮点型统称算数类型。

3.4、C++算数运算符

// arith.cpp -- some C++ arithmetic
#include <iostream>
int main()
{
    using namespace std;
    float hats, heads;

    cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point
    cout << "Enter a number: ";
    cin >> hats;
    cout << "Enter another number: ";
    cin >> heads;

    cout << "hats = " << hats << "; heads = " << heads << endl;
    cout << "hats + heads = " << hats + heads << endl;
    cout << "hats - heads = " << hats - heads << endl;
    cout << "hats * heads = " << hats * heads << endl;
    cout << "hats / heads = " << hats / heads << endl;
    // cin.get();
    // cin.get();
    return 0;
}
/*
Enter a number: 50.25
Enter another number: 11.17
hats = 50.250000; heads = 11.170000
hats + heads = 61.419998
hats - heads = 39.080002
hats * heads = 561.292480
hats / heads = 4.498657
*/

在C++中,对于float,仅保证6位或7位有效位

3.4.1、运算符优先级

C++的运算符优先级

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u2y9NYPn-1691999308836)(.\pics\8-10-0.png)]

后续

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x4wxWQpS-1691999308836)(.\pics\8-10-1.png)]

后续

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zERjaCJ7-1691999308836)(.\pics\8-10-2.png)]

3.4.2、除法分支

// divide.cpp -- integer and floating-point division
#include <iostream>
int main()
{
    using namespace std;
    cout.setf(ios_base::fixed, ios_base::floatfield);
    cout << "Integer division: 9/5 = " << 9 / 5  << endl;
    cout << "Floating-point division: 9.0/5.0 = ";
    cout << 9.0 / 5.0 << endl;
    cout << "Mixed division: 9.0/5 = " << 9.0 / 5  << endl;
    cout << "double constants: 1e7/9.0 = ";
    cout << 1.e7 / 9.0 <<  endl;
    cout << "float constants: 1e7f/9.0f = ";
    cout << 1.e7f / 9.0f <<  endl;
    // cin.get();
    return 0;
}
/*
Integer division: 9/5 = 1
Floating-point division: 9.0/5.0 = 1.800000
Mixed division: 9.0/5 = 1.800000
double constants: 1e7/9.0 = 1111111.111111
float constants: 1e7f/9.0f = 1111111.125000
*/

最后两行的相对精度表明,如果两个操作数都是double类型,则结果为double类型;如果两个操作数都是float类型,则结果为float类型。浮点常量在默认的情况下,为double类型。

运算符重载

3.4.3、求模运算符

// modulus.cpp -- uses % operator to convert lbs to stone
#include <iostream>

int main() {
	using namespace std;
	const int Lbs_per_stn = 14;
	int lbs;

	cout << "Enter your weight in pounds: ";
	cin >> lbs;
	int stone = lbs / Lbs_per_stn;      // whole stone
	int pounds = lbs % Lbs_per_stn;     // remainder in pounds
	cout << lbs << " pounds are " << stone
	     << " stone, " << pounds << " pound(s).\n";
	// cin.get();
	// cin.get();
	return 0;
}
/*
Enter your weight in pounds: 181
181 pounds are 12 stone, 13 pound(s).
*/

3.4.4、类型转换

C++中会有多种类型的转换

  • 赋值时,类型不同,会进行转换
  • 表达式中包含不同的类型时,C++将对值进行转换
  • 将参数传递给函数时,C++将对值进行转换

对于类型的转换,可能会出现一些问题。

image-20230810110055454
// assign.cpp -- type changes on assignment
#include <iostream>

int main() {
	using namespace std;
	cout.setf(ios_base::fixed, ios_base::floatfield);
	float tree = 3;     // int converted to float
	int guess = 3.9832; // float converted to int
	int debt = 7.2E12;  // result not defined in C++
	cout << "tree = " << tree << endl;
	cout << "guess = " << guess << endl;
	cout << "debt = " << debt << endl;
	// cin.get();
	return 0;
}

/*
tree = 3.000000
guess = 3
debt = 2147483647
*/

在将整数变量初始化为浮点值时,有时编译器将会警告。int变量无法存储7.2E12,这导致C++没有对结果进行定义的情况发生。

整型级别

有符号整型按级别从高到低依次是:long long、long、int、short和signed char。

无符号整型的排列顺序与有符号整型相同。类型char、signed char和unsigned char的级别相同。类型bool的级别最低。wchar_t、char16_t和char32_t的级别与其底层类型相同。

强制类型转换

static_cast<>可用于将值从一种数值类型转换为另一种数值类型。

static_cast (value)

// typecast.cpp -- forcing type changes
#include <iostream>

int main() {
	using namespace std;
	int auks, bats, coots;

	// the following statement adds the values as double,
	// then converts the result to int
	auks = 19.99 + 11.99;

	// these statements add values as int
	bats = (int) 19.99 + (int) 11.99;   // old C syntax
	coots = int (19.99) + int (11.99);  // new C++ syntax
	cout << "auks = " << auks << ", bats = " << bats;
	cout << ", coots = " << coots << endl;

	char ch = 'Z';
	cout << "The code for " << ch << " is ";    // print as char
	cout << int(ch) << endl;                    // print as int
	cout << "Yes, the code is ";
	cout << static_cast<int>(ch) << endl;       // using static_cast
	// cin.get();
	return 0;
}
/*
auks = 31, bats = 30, coots = 30
The code for Z is 90
Yes, the code is 90
*/

3.4.5、auto声明

在初始化声明中,使用关键字auto,而不指定变量的类型,编译器将把变量的类型设置成与初始值相同

auto n=100;		//n is int
auto x=1.5;		//x is double
auto y=1.3e12L;	//y is long double

4、复合类型

4.1、数组

声明需要以下3点

  • 存储在每个元素中的值的类型
  • 数组名
  • 数组中的元素数

声明数组的通用格式如下:

typeName arrayName[arraySize];

float loans[20];

loans的类型不是“数组”,而是“float数组”。这强调了loans数组是使用float类型创建的。为复合类型

// arrayone.cpp -- small arrays of integers
#include <iostream>

int main() {
	using namespace std;
	int yams[3];    // creates array with three elements
	yams[0] = 7;    // assign value to first element
	yams[1] = 8;
	yams[2] = 6;

	int yamcosts[3] = {20, 30, 5}; // create, initialize array
// NOTE: If your C++ compiler or translator can't initialize
// this array, use static int yamcosts[3] instead of
// int yamcosts[3]

	cout << "Total yams = ";
	cout << yams[0] + yams[1] + yams[2] << endl;
	cout << "The package with " << yams[1] << " yams costs ";
	cout << yamcosts[1] << " cents per yam.\n";
	int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1];
	total = total + yams[2] * yamcosts[2];
	cout << "The total yam expense is " << total << " cents.\n";

	cout << "\nSize of yams array = " << sizeof yams;
	cout << " bytes.\n";
	cout << "Size of one element = " << sizeof yams[0];
	cout << " bytes.\n";
	// cin.get();
	return 0;
}
/*
Total yams = 21
The package with 8 yams costs 30 cents per yam.
The total yam expense is 410 cents.

Size of yams array = 12 bytes.
Size of one element = 4 bytes.
*/

sizeof运算符返回类型或数据对象的长度(单位为字节)。注意,如果将sizeof运算符用于数组名,得到的将是整个数组的字节数。但如果将sizeof用于数组元素,则得到的将是元素的长度(单位为字节)。

初始化的方法

初始化禁止缩窄转换。

long plifs[]={25,92,3.0};		//not allowed
char slifs[4]{'h','i',12208,'\0'};	//not allowed
char tlifs[4]{'h','i',112,'\0'};	//allowed

第1条语句不能通过编译,因为将浮点数转换为整型是缩窄操作,即使浮点数的小数点后面为零。

第2条语句也不能通过编译,因为12208超出了char变量的取值范围(这里假设char变量的长度为8位)。

第3条语句可通过编译,因为虽然112是一个int值,但它在char变量的取值范围内。

C++标准模板库(STL)提供了一种数组替代品——模板类vector,而C++11新增了模板类array。

4.2、字符串

可以使用字符数组初始化为字符串,但需要使用大量单引号,且必须加上空字符。可以使用括号括起字符串,这种字符串被称为字符串常量或字符串字面值。

char bird[11]="Mr. Cheeps";
char fish[]="Bubbles";

**注意:**字符常量(使用单引号)和字符串常量(使用双引号)不能互换。

char shirt_size ='s';	//this is fine
char shirt_size ="S";	//illegal type mismatch

字符串的拼接

**注意:**拼接时不会在被连接的字符串之间添加空格,第二个字符串的第一个字符将紧跟在第一个字符串的最后一个字符(不考虑\0)后面。第一个字符串中的\0字符将被第二个字符串的第一个字符取代。

// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring>  // for the strlen() function

int main() {
	using namespace std;
	const int Size = 15;
	char name1[Size];               // empty array
	char name2[Size] = "C++owboy";  // initialized array
	// NOTE: some implementations may require the static keyword
	// to initialize the array name2

	cout << "Howdy! I'm " << name2;
	cout << "! What's your name?\n";
	cin >> name1;
	cout << "Well, " << name1 << ", your name has ";
	cout << strlen(name1) << " letters and is stored\n";
	cout << "in an array of " << sizeof(name1) << " bytes.\n";
	cout << "Your initial is " << name1[0] << ".\n";
	name2[3] = '\0';                // set to null character
	cout << "Here are the first 3 characters of my name: ";
	cout << name2 << endl;
	// cin.get();
	// cin.get();
	return 0;
}
/*
Howdy! I'm C++owboy! What's your name?
Basicman
Well, Basicman, your name has 8 letters and is stored
in an array of 15 bytes.
Your initial is B.
Here are the first 3 characters of my name: C++
*/

sizeof运算符指出整个数组的长度:15字节;strlen()函数返回的是存储在数组中的字符串的长度,而不是数组本身的长度。另外,strlen()只计算可见的字符,而不把空字符计算在内,因此为8。

可以将name2[3]设置为空字符。这使得字符号在第3个字符后即结束,达到截断字符串的效果。

在这里插入图片描述

字符串的输入

// instr1.cpp -- reading more than one string
#include <iostream>
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter your name:\n";
    cin >> name;
    cout << "Enter your favorite dessert:\n";
    cin >> dessert;
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    // cin.get();
	// cin.get();
    return 0; 
}
/*
Enter your name:
Ali dreeb
Enter your favorite dessert:
I have some delicious dreeb for you, Ali.
*/

如下图所示:
在这里插入图片描述

  • 面向行的输入:getline()

cin.getline(name,20)

// instr2.cpp -- reading more than one word with getline
#include <iostream>
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter your name:\n";
    cin.getline(name, ArSize);  // reads through newline
    cout << "Enter your favorite dessert:\n";
    cin.getline(dessert, ArSize);
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    // cin.get();
    return 0; 
}
/*
Enter your name:
Mai Par
Enter your favorite dessert:
Chocolate Mousse
I have some delicious Chocolate Mousse for you, Mai Par.
*/
  • 面向行的输入:get()
cin.get(name,Arsize);
cin.get();
cin.get(dessert,Arsize);

//另一种方式
cin.get(name,Arsize).get();
#include <iostream>

int main() {
	using namespace std;
	const int ArSize = 20;
	char name[ArSize];
	char dessert[ArSize];

	cout << "Enter your name:\n";
	cin.get(name, ArSize).get();    // read string, newline
	cout << "Enter your favorite dessert:\n";
	cin.get(dessert, ArSize).get();
	cout << "I have some delicious " << dessert;
	cout << " for you, " << name << ".\n";
	// cin.get();
	return 0;
}

/*
Enter your name:
Mai Per
Enter your favorite dessert:
Chocolate Mousse
I have some delicious Chocolate Mousse for you, Mai Per.
*/

混合输入字符串和数字

// numstr.cpp -- following number input with line input
#include <iostream>

int main() {
	using namespace std;
	cout << "What year was your house built?\n";
	int year;
	cin >> year;	//可与下面结合(cin>>year).get()或(cin>>year).get(ch)
//	cin.get();  或cin.get(ch)
	cout << "What is its street address?\n";
	char address[80];
	cin.getline(address, 80);
	cout << "Year built: " << year << endl;
	cout << "Address: " << address << endl;
	cout << "Done!\n";
	// cin.get();
	return 0;
}

4.3、string类

// strtype1.cpp -- using the C++ string class
#include <iostream>
#include <string>               // make string class available

int main() {
	using namespace std;
	char charr1[20];            // create an empty array
	char charr2[20] = "jaguar"; // create an initialized array
	string str1;                // create an empty string object
	string str2 = "panther";    // create an initialized string

	cout << "Enter a kind of feline: ";
	cin >> charr1;
	cout << "Enter another kind of feline: ";
	cin >> str1;                // use cin for input
	cout << "Here are some felines:\n";
	cout << charr1 << " " << charr2 << " "
	     << str1 << " " << str2 // use cout for output
	     << endl;
	cout << "The third letter in " << charr2 << " is "
	     << charr2[2] << endl;
	cout << "The third letter in " << str2 << " is "
	     << str2[2] << endl;    // use array notation
	// cin.get();
	// cin.get();

	return 0;
}
/*
Enter a kind of feline: ocelot
Enter another kind of feline: tiger
Here are some felines:
ocelot jaguar tiger panther
The third letter in jaguar is g
The third letter in panther is n
*/

赋值、拼接

使用string类时,某些操作比使用数组时更简单。例如,不能将一个数组赋给另一个数组,但可以将一个string对象赋给另一个string对象。

string str3;
str3=str1+str2;
str1+=str2;

例子

int main() {
	using namespace std;
	string s1 = "penguin";
	string s2, s3;

	cout << "You can assign one string object to another: s2 = s1\n";
	s2 = s1;
	cout << "s1: " << s1 << ", s2: " << s2 << endl;
	cout << "You can assign a C-style string to a string object.\n";
	cout << "s2 = \"buzzard\"\n";
	s2 = "buzzard";
	cout << "s2: " << s2 << endl;
	cout << "You can concatenate strings: s3 = s1 + s2\n";
	s3 = s1 + s2;
	cout << "s3: " << s3 << endl;
	cout << "You can append strings.\n";
	s1 += s2;
	cout << "s1 += s2 yields s1 = " << s1 << endl;
	s2 += " for a day";
	cout << "s2 += \" for a day\" yields s2 = " << s2 << endl;

	//cin.get();
	return 0;
}
/*
You can assign one string object to another: s2 = s1
s1: penguin, s2: penguin
You can assign a C-style string to a string object.
s2 = "buzzard"
s2: buzzard
You can concatenate strings: s3 = s1 + s2
s3: penguinbuzzard
You can append strings.
s1 += s2 yields s1 = penguinbuzzard
s2 += " for a day" yields s2 = buzzard for a day
*/

其他操作

strcpy(charr1,charr2); //copy charr2 to charr1

strcat(charr1,charr2); //append contents of charr2 to char1

// strtype3.cpp -- more string class features
#include <iostream>
#include <string>               // make string class available
#include <cstring>              // C-style string library
int main()
{
    using namespace std;
    char charr1[20]; 
    char charr2[20] = "jaguar"; 
    string str1;  
    string str2 = "panther";

    // assignment for string objects and character arrays
    str1 = str2;                // copy str2 to str1
    strcpy(charr1, charr2);     // copy charr2 to charr1
 
    // appending for string objects and character arrays
    str1 += " paste";           // add paste to end of str1
    strcat(charr1, " juice");   // add juice to end of charr1

    // finding the length of a string object and a C-style string
    int len1 = str1.size();     // obtain length of str1
    int len2 = strlen(charr1);  // obtain length of charr1
 
    cout << "The string " << str1 << " contains "
         << len1 << " characters.\n";
    cout << "The string " << charr1 << " contains "
         << len2 << " characters.\n";
    // cin.get();

    return 0; 
}
/*
The string panther paste contains 13 characters.
The string jaguar juice contains 12 characters.
*/

string类I/O

#include <iostream>
#include <string>               // make string class available
#include <cstring>              // C-style string library

int main() {
	using namespace std;
	char charr[20];
	string str;

	cout << "Length of string in charr before input: "
	     << strlen(charr) << endl;
	cout << "Length of string in str before input: "
	     << str.size() << endl;
	cout << "Enter a line of text:\n";
	cin.getline(charr, 20);     // indicate maximum length
	cout << "You entered: " << charr << endl;
	cout << "Enter another line of text:\n";
	getline(cin, str);          // cin now an argument; no length specifier
	cout << "You entered: " << str << endl;
	cout << "Length of string in charr after input: "
	     << strlen(charr) << endl;
	cout << "Length of string in str after input: "
	     << str.size() << endl;
	// cin.get();
	return 0;
}
/*
Length of string in charr before input: 1
Length of string in str before input: 0
Enter a line of text:
puagj letter
You entered: puagj letter
Enter another line of text:
fghjdfgh hjd
You entered: fghjdfgh hjd
Length of string in charr after input: 12
Length of string in str after input: 12
*/

其他形式的字符串字面值

除了char类型,C++还有类型wchar_t;而C++11新增了类型char16_t和char32_t。可以分别使用前缀L、u和U表示

wchar_t title[]=L"Chief Ast";
char16_t name[]=u"FFF WANG"
char32_t car[]=U"Humber Super snipe"

Q

01、sizeof()&strlen()

char str[20]="0123456789";
int a=strlen(str);         // a=10; >>>> strlen 计算字符串的长度,以结束符 0x00 为字符串结束。
int b=sizeof(str);         // 而 b=20; >>>> sizeof 计算的则是分配的数组 str[20] 所占的内存空间的大小,不受里面存储的内容改变。  

对于指针

char* ss = "0123456789";
sizeof(ss) 结果 4 ===》ss 是指向字符串常量的字符指针,sizeof 获得的是一个指针的之所占的空间,应该是长整型的,所以是 4。
sizeof(*ss) 结果 1 ===》*ss 是第一个字符 其实就是获得了字符串的第一位 '0' 所占的内存空间,是 char 类型的,占了 1 位
strlen(ss)= 10      ===》 如果要获得这个字符串的长度,则一定要使用 strlen。strlen 用来求字符串的长度;而 sizeof 是用来求指定变量或者变量类型等所占内存大小。

() << endl;
// cin.get();
return 0;
}
/*
Length of string in charr before input: 1
Length of string in str before input: 0
Enter a line of text:
puagj letter
You entered: puagj letter
Enter another line of text:
fghjdfgh hjd
You entered: fghjdfgh hjd
Length of string in charr after input: 12
Length of string in str after input: 12
*/


**其他形式的字符串字面值**

除了char类型,C++还有类型wchar_t;而C++11新增了类型char16_t和char32_t。可以分别使用前缀L、u和U表示

wchar_t title[]=L"Chief Ast";
char16_t name[]=u"FFF WANG"
char32_t car[]=U"Humber Super snipe"






# Q

## 01、sizeof()&strlen()

```c++
char str[20]="0123456789";
int a=strlen(str);         // a=10; >>>> strlen 计算字符串的长度,以结束符 0x00 为字符串结束。
int b=sizeof(str);         // 而 b=20; >>>> sizeof 计算的则是分配的数组 str[20] 所占的内存空间的大小,不受里面存储的内容改变。  

对于指针

char* ss = "0123456789";
sizeof(ss) 结果 4 ===》ss 是指向字符串常量的字符指针,sizeof 获得的是一个指针的之所占的空间,应该是长整型的,所以是 4。
sizeof(*ss) 结果 1 ===》*ss 是第一个字符 其实就是获得了字符串的第一位 '0' 所占的内存空间,是 char 类型的,占了 1 位
strlen(ss)= 10      ===》 如果要获得这个字符串的长度,则一定要使用 strlen。strlen 用来求字符串的长度;而 sizeof 是用来求指定变量或者变量类型等所占内存大小。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值