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 variablecout << "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 valueint main() {using namespace std;short sam = SHRT_MAX;     // initialize a variable to max valueunsigned short sue = sam;// okay if variable sam already definedcout << "Sam has " << sam << " dollars and Sue has " << sue;cout << " dollars deposited." << endl<< "Add $1 to each account." << endl << "Now ";sam = sam + 1;	//32767+1,溢出,-32768sue = sue + 1;cout << "Sam has " << sam << " dollars and Sue has " << sue;cout << " dollars deposited.\nPoor Sam!" << endl;sam = ZERO;sue = ZERO;		//0-1,溢出,65536cout << "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 literalint waist = 0x42;   // hexadecimal integer literalint inseam = 042;   // octal integer literalcout << "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 basecout << "waist = " << waist << " (hexadecimal for 42)" << endl;cout << oct;      // manipulator for changing number basecout << "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 variablecout << "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 chint i = ch;          // store same code in an intcout << "The ASCII code for " << ch << " is " << i << endl;cout << "Add one to the character code:" << endl;ch = ch + 1;          // change character code in chi = ch;               // save new character code in icout << "The ASCII code for " << ch << " is " << i << endl;// using the cout.put() member function to display a charcout << "Displaying char ch using cout.put(ch): ";cout.put(ch);// using cout.put() to display a char constantcout.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-pointfloat tub = 10.0 / 3.0;     // good to about 6 placesdouble mint = 10.0 / 3.0;   // good to about 15 placesconst 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-pointcout << "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 stoneint pounds = lbs % Lbs_per_stn;     // remainder in poundscout << 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 floatint guess = 3.9832; // float converted to intint 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 intauks = 19.99 + 11.99;// these statements add values as intbats = (int) 19.99 + (int) 11.99;   // old C syntaxcoots = int (19.99) + int (11.99);  // new C++ syntaxcout << "auks = " << auks << ", bats = " << bats;cout << ", coots = " << coots << endl;char ch = 'Z';cout << "The code for " << ch << " is ";    // print as charcout << int(ch) << endl;                    // print as intcout << "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 elementsyams[0] = 7;    // assign value to first elementyams[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() functionint main() {using namespace std;const int Size = 15;char name1[Size];               // empty arraychar name2[Size] = "C++owboy";  // initialized array// NOTE: some implementations may require the static keyword// to initialize the array name2cout << "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 charactercout << "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 newlinecout << "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, newlinecout << "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 availableint main() {using namespace std;char charr1[20];            // create an empty arraychar charr2[20] = "jaguar"; // create an initialized arraystring str1;                // create an empty string objectstring str2 = "panther";    // create an initialized stringcout << "Enter a kind of feline: ";cin >> charr1;cout << "Enter another kind of feline: ";cin >> str1;                // use cin for inputcout << "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 arraysstr1 = str2;                // copy str2 to str1strcpy(charr1, charr2);     // copy charr2 to charr1// appending for string objects and character arraysstr1 += " paste";           // add paste to end of str1strcat(charr1, " juice");   // add juice to end of charr1// finding the length of a string object and a C-style stringint len1 = str1.size();     // obtain length of str1int len2 = strlen(charr1);  // obtain length of charr1cout << "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 libraryint 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 lengthcout << "You entered: " << charr << endl;cout << "Enter another line of text:\n";getline(cin, str);          // cin now an argument; no length specifiercout << "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 是用來求指定變量或者變量類型等所占內存大小。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/37121.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/37121.shtml
英文地址,請注明出處:http://en.pswp.cn/news/37121.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

深入探究QCheckBox的三種狀態及其用法

文章目錄 引言&#xff1a;三種狀態一、未選中狀態&#xff08;0&#xff09;&#xff1a;二、選中狀態&#xff08;2&#xff09;&#xff1a;三、部分選中狀態&#xff08;1&#xff09;&#xff1a; 判斷方法結論&#xff1a; 引言&#xff1a; QCheckBox是Qt框架中常用的復…

html css實現愛心

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><style>/* 愛心 */.lo…

修改Linux中SSH的端口

文章目錄 修改Linux中SSH的端口Linux中默認的ssh端口關閉SELinux測試新端口 修改Linux中SSH的端口 Linux中默認的ssh端口 使用root用戶操作 修改前先備份ssh_config cp /etc/ssh/sshd_config /etc/ssh/sshd_config_date "%Y%m%d%H%M%S"修改配置文件&#xff0c;找…

結構體的定義與賦值

1、結構體定義 首先定義一個學生結構體&#xff0c;如下所示&#xff1a; struct Student {int num;char name[32];char sex;int age; }; 接著在主函數中對學生進行聲明&#xff0c;如下所示&#xff1a; #include<iostream> using namespace std;struct Student {in…

2023Robocom省賽(本科組)

RC-u1 亞運獎牌榜 題目鏈接&#xff1a;PTA | 程序設計類實驗輔助教學平臺 (pintia.cn) 題目&#xff1a; 2022 年第 19 屆亞運會即將在杭州召開&#xff0c;杭州已經做好準備歡迎全亞洲的觀眾一同參與亞運盛會了&#xff01; 你正在開發一款跟亞運獎牌計算相關的 App。給定…

“深入探究JVM內部結構與工作原理:解析Java虛擬機“

標題&#xff1a;深入探究JVM內部結構與工作原理 摘要&#xff1a;本文將深入探究Java虛擬機&#xff08;JVM&#xff09;的內部結構與工作原理。我們將介紹JVM的基本組成部分&#xff0c;包括類加載器、運行時數據區和執行引擎。同時&#xff0c;我們將通過一個示例代碼來說明…

直接在html中引入Vue.js的cdn來實現一個簡單的上傳圖片組件

摘要 當使用 Vue.js 的 CDN 來實現一個簡單的上傳圖片組件時&#xff0c;你可以利用 Vue 的數據綁定和事件處理能力&#xff0c;結合 HTML 和 CSS&#xff0c;輕松地創建一個交互式的圖片上傳界面。以下是一個示例&#xff1a; 代碼結構 index.html <!DOCTYPE html> &…

LVS集群和分布式

LVS 一.集群和分布式概念 1.1 集群 在計算機領域&#xff0c;集群早在 1960 年就出現&#xff0c;隨著互聯網和計算機相關技術的發展&#xff0c;現在 集群這一技術已經在各大互聯網公司普及。 1.1.1 集群概念 計算機集群指一組通過計算機網絡連接的計算機&#xff0c;它們…

Rust 重載運算符|復數結構的“加減乘除”四則運算

復數 基本概念 復數定義 由實數部分和虛數部分所組成的數&#xff0c;形如a&#xff0b;bi 。 其中a、b為實數&#xff0c;i 為“虛數單位”&#xff0c;i -1&#xff0c;即虛數單位的平方等于-1。 a、b分別叫做復數a&#xff0b;bi的實部和虛部。 當b0時&#xff0c;a&…

前后端分離------后端創建筆記(06)新增接口頁面布局

本文章轉載于【SpringBootVue】全網最簡單但實用的前后端分離項目實戰筆記 - 前端_大菜007的博客-CSDN博客 僅用于學習和討論&#xff0c;如有侵權請聯系 源碼&#xff1a;https://gitee.com/green_vegetables/x-admin-project.git 素材&#xff1a;https://pan.baidu.com/s/…

Kubernetes入門 四、Pod核心

目錄 什么是PodPod與容器不同Pod如何管理多個容器Pod的管理-工作負載K8s中的資源清單創建使用Pod直接創建Pod使用 Deployment 創建Pod 環境變量重啟策略鏡像拉取策略訪問 DNS 的策略資源限制初始化容器臨時容器&#xff08;了解&#xff09; 什么是Pod Pod 是可以在 Kubernete…

Azure添加網絡接口

添加網絡接口的意義 在 Azure 上&#xff0c;為虛擬機添加網絡接口的意義包括以下幾個方面&#xff1a; 擴展網絡帶寬&#xff1a;通過添加多個網絡接口&#xff0c;可以增加虛擬機的網絡帶寬&#xff0c;提高網絡傳輸速度和數據吞吐量。實現網絡隔離&#xff1a;每個網絡接口…

zabbix-6.4 監控 MySQL

目錄 1、rpm安裝zabbix_agentd服務 2、編寫zabbix_agentd.conf文件 3、編寫模板文件 4、創建mysql用戶并賦權限 5、創建.my.cnf文件 6、將規則添加到SELinux策略中 注意&#xff1a; 若模板無法讀取.my.cnf 信息&#xff0c;從而導致監控報錯&#xff0c;可以嘗試修改模…

虛樹

虛樹是用來優化樹形dp的東西&#xff0c;它的轉移是從一些特殊點&#xff0c;向根節點轉移&#xff0c;期間它有用的轉移點比較特殊。通常詢問次數較多&#xff0c;但特殊點總和較少&#xff0c;就可以每次詢問先建虛樹再跑dp。單調棧建虛樹 O ( k l o g n ) O(klogn) O(klogn)…

別人直播的時候怎么錄屏?分享一些錄屏方法

?隨著互聯網的快速發展&#xff0c;直播已經成為人們日常生活中不可或缺的一部分。但是&#xff0c;有時候我們可能會錯過某些重要的直播內容&#xff0c;這時候就需要錄屏來保存和觀看。那么&#xff0c;如何錄屏別人的直播呢&#xff1f;本文將分享一些錄屏方法和技巧&#…

【Python機器學習】實驗11 神經網絡-感知器

文章目錄 人工神經網絡感知機二分類模型算法 1. 基于手寫代碼的感知器模型1.1 數據讀取1.2 構建感知器模型1.3 實例化模型并訓練模型1.4 可視化 2. 基于sklearn的感知器實現2.1 數據獲取與前面相同2.2 導入類庫2.3 實例化感知器2.4 采用數據擬合感知器2.5 可視化 實驗1 將上面數…

SpringBoot復習:(50)TransactionManager是哪里來的?是什么類型的?

運行結果&#xff1a; 可見它的類型是DataSourceTransactionManager.它是通過自動配置創建的。

rust怎么做大型項目管理?學好cargo和mod是關鍵

一提到大型項目開發&#xff0c;大家都會以Java作為標準&#xff0c;為什么呢&#xff1f; 一個是Java生態有很多以Maven為代表的成熟的項目管理工具&#xff0c;另一個是基于package的模塊管理模式&#xff0c;提供了非常好的功能內聚和模塊間解耦&#xff0c;而同樣的rust也有…

PHP先等比縮放再無損裁剪圖片【實例源碼】

很多人在使用程序裁剪圖片時,是在原圖上直接裁剪,這樣的裁剪結果是使得圖片變得不完整了,理想的做法是先等比縮小圖片,再把多余的部分裁掉,這樣會保留更多的圖片信息。 實現代碼: <?php/*** 說明:函數功能是把一個圖像裁剪為任意大小的圖像,圖像不變形** @param …

類型轉換與索引使用與字段緩存問題

** 1: 類型轉換與索引使用** 假設你有一個MySQL表格 users&#xff0c;其中有一個 age 列&#xff0c;數據類型是整數&#xff08;INT&#xff09;&#xff0c;并且為該列創建了一個索引。然后你執行以下查詢&#xff1a; sqlCopy code SELECT * FROM users WHERE age 25;在…