preface
This article mainly introduces the concepts of string and array in C/C + +
1. String storage variable
1.1 project requirements
On the basis of item 2, the user name and password are stored in strings
1.2 project realization
login2.cpp#include <iostream> #include <Windows.h> #Include < string > / / String file in std namespace, the standard library of C + + is string, and that of C is string h using namespace std; int main(void) { string loginName; string pwd; cout << "Please enter account number:"; cin >> loginName; cout << "Please input a password:"; cin >> pwd; system("pause"); cout << "Your account number is" << loginName << endl; cout << "Your password is:" << pwd << endl; system("pause"); return 0; }
Operation results:
1.3 knowledge bag: the concept of string
1.3.1 basic concepts
a string is an "ordered" sequence of 0 or more "characters".
1.3.2 string constants
"Literal" string constant, which is required to be expanded with "".
printf(“name=%s”, “heihei”); // C language output string,% s is used to match the string
cout << “heihei”; // C + + output string
1.3.3 representation of string variables
In C language, an array of char type is used to store string variables
Note: in C language, there is no special string type.
In C + +, the std::string type is used to represent string variables.
1.3.4 string Terminator
In c language, in order to facilitate the storage of strings, it is required to store a 0 (one byte) after the last character.
This 0, called "string terminator", is often represented by '\ 0'.
In C + + language, there is no string terminator at end of the string!
In actual storage, depending on the compiler, a string terminator may or may not be stored at last.
2.C + + style string
2.1 definition and initialization of string variable
#include <iostream> #include <Windows.h> #include <string> using namespace std; int main(void) { //1. Define and assign c + + style string girlFriend1; girlFriend1 = "Faye Wong"; string girlFriend2; girlFriend2 = girlFriend1; //2. Initialization string girlFriend3("Zhou Xun"); string girlFriend4(girlFriend3); string girlFriend5(10,'a');//Equivalent to string girlfriend5 ("aaaaaaaaaaaaaaaa"); string girlFriend6;//No assignment is an empty string cout << "girlFriend1=" << girlFriend1 << endl; cout << "girlFriend2=" << girlFriend2 << endl; cout << "girlFriend3=" << girlFriend3 << endl; cout << "girlFriend4=" << girlFriend4 << endl; cout << "girlFriend5=" << girlFriend5 << endl; cout << "girlFriend6=" << girlFriend6 << endl; //c language style char a[20] = "hello world"; char b[20] = { 'h','e','l','l','o',' ','w','o','r','l','d','\0' }; char c[] = "hello world"; char d[] = { 'h','e','l','l','o',' ','w','o','r','l','d', 0 }; printf("a = %s\n", a); printf("b = %s\n", b); printf("c = %s\n", c); printf("d = %s\n", d); //The difference between string and character array: string must be an array of char, but char array may not be a string; //The char array ending with the number 0 (equivalent to the character '\ 0') is a string, but if the char array does not end with the number 0, it is not a string, but an ordinary character array, so the string is a special char array. //A string definition that either specifies a character length or ends with 0 or '\ 0'. //Error demonstration: garbled code will appear char buf[] = { 'a', 'b', 'c' }; printf("buf = %s\n", buf); system("pause"); return 0; }
2.2 input and output of string variable
#include <iostream> #include <Windows.h> #include <string> using namespace std; int main0302(void) { //demo1 - the input of the string starts from the first non blank word and stops when a blank character is encountered //Blank characters refer to: space, tab, carriage return //string job; //Cout < < "what do you do?"<< endl; //cin >> job; //Cout < < do "< < job < < income should be very good<< endl; demo2 - Automatically skip white space characters //string university; //string profession; //Cout < < "what major did you study in that university?"<< endl; //cin >> university >> profession; //Cout < < University < < professional < < professional < < very good<< endl; demo3 - Cyclic input //string food; //int count = 0; //Cout < < "what food do you like?"<< endl; //While (CIN > > food) / / when the user enters Ctrl + z and enters, CIN > > food returns 0, and 0 is false //{ // Cout < < I like to eat < < Food < < endl; // Cout < < "what else do you like to eat?"<< endl; // count++; //} //Cout < < things you like "< < count < < species" < < endl; //demo4 - enter a line of getline string addr; cout << "Where are you going?" << endl; getline(cin, addr);//Read a row of data and write it (including spaces) to the end of '\ n', and '\ n' will be discarded //empty method if (addr.empty() == true) { cout << "You don't know, you salted fish without dreams!" << endl; return 1; } else { cout << "I happen to be going too" << addr << ",I'll take you" << endl; } //size() and length() are completely equivalent //Length refers to the number of bytes occupied by the string. If Chinese characters are included, the total number of bytes is different from the number of Chinese characters cout << "addr The length of the is:" << addr.size() << endl; cout << "addr The length of the is:" << addr.length() << endl; system("pause"); return 0; }
2.3 comparison of string
#include <iostream> #include <Windows.h> using namespace std; int main0303(void) { /* String comparison: Starting from the first character of the string, the corresponding characters are compared one by one until unequal characters are encountered. Comparison operators are: > >= < <= == The result of comparison operation: Logic true, logic false "123" < "1230" really "19" > "123456789" really "2" > "1999" really "123" == "123" really "123" == "1230" false c Language string. This method cannot be used for string comparison. */ string myGirl = "Xiao Fang"; string yourGirl; cout << "What's your favorite girl?" << endl; cin >> yourGirl; if (yourGirl == myGirl) { cout << "Hello, brother!" << endl; } else { cout << "I wish you green" << endl; } system("pause"); return 0; }
2.4 addition of string
#include <iostream> #include <Windows.h> using namespace std; int main0304(void) { //The string on the left side of + and the string on the right side of + are directly spliced into a new string //Pay attention to the order. (this method is not supported for strings in C language) string a = "heihei"; string b = "wakaka"; string c; c = a + b; cout << c << endl; c += "yi"; cout << c << endl; system("pause"); return 0; }
3. Array
3.1 definition of array
array is an ordered "combination" of multiple elements.
int a[5] / / defines an array a containing five elements, each of which is an int variable
3.2 initialization of array
#include <iostream> #include <Windows.h> #include <stdio.h> using namespace std; int main0306(void) { //While defining the array, set the element values in the array. int a[8] = { 20,45,20,33,55 }; printf("%d,%d,%d,%d,%d\n", a[0], a[1], a[2], a[3], a[4]); cout << a[0] << "," << a[1] << "," << a[2] << "," << a[3] << "," << a[4] << endl; //Initialize all elements of the array to 0 int b[8] = { 0 }; //But this initializes the first element of the array to 1 and all other values to 0 int c[8] = { 1 }; //Define Array d, which contains 3 elements! // Automatically calculate the capacity of the array according to the "initialization list" int d[] = { 1,2,5 }; //It is only supported by C compiler, but not in C + + compiler, that is, it cannot be used in C + + program. int exercises[7] = { [1] = 1, //a[1] = 1 [3] = 2, //a[3] = 2 //No member specified, initialized to 0 }; system("pause"); return 0; }
4.C language style string
4.1 definition of char array string
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <Windows.h> using namespace std; int main0305(void) { /* * string constant "Literal string constant, which is required to be expanded with ''. printf("name=%s", "Tree"); //C Language output string,% s is used to match the string cout << "Tree"; //C++Mode output string * Representation of string variables In C language, an array of char type is used to store string variables Note: in C language, there is no special string type. In C + +, the std::string type is used to represent string variables. * In c language, in order to facilitate the storage of strings, it is required to store a 0 (one byte) after the last character. The common character string is called "0", which means the end of the string. In C + + language, there is no string terminator at end of the string! In actual storage, depending on the compiler, a string terminator may or may not be stored at last. * */ char a[20] = "hello world"; char b[20] = { 'h','e','l','l','o',' ','w','o','r','l','d','\0' }; char c[] = "hello world"; char d[] = { 'h','e','l','l','o',' ','w','o','r','l','d', 0 }; printf("a = %s\n", a); printf("b = %s\n", b); printf("c = %s\n", c); printf("d = %s\n", d); //The difference between string and character array: the string must be an array of char, but the array of char may not be a string; //The char array ending with the number 0 (equivalent to the character '\ 0') is a string, but if the char array does not end with the number 0, it is not a string, but an ordinary character array, so the string is a special char array. //A string definition that either specifies a character length or ends with 0 or '\ 0'. //Error demonstration: garbled code will appear char buf[] = { 'a', 'b', 'c' };//This is an array of characters printf("buf = %s\n", buf); char name[10]; printf("Please enter your name:"); scanf("%s", name); printf("Your name is:%s\n",name); cout << "Please enter your name:"; cin >> name; cout << "Your name is:" << name << endl; system("pause"); return 0; }
4.2 input and output of char array string and emptying input buffer
#define _CRT_SECURE_NO_WARNINGS #define NOMINMAX #include <stdio.h> #include <iostream> #include <Windows.h> using namespace std; void clearBuff() { char tmp; while ((tmp = getchar()) != '\n');//If it is not carriage return, the characters in the input buffer are read } int main(void) { char name[16]; char addr[64]; printf("Dare you ask the name of mushroom cool?\n"); scanf("%s", name); //scanf reads the end of the carriage return, which is still in the input buffer //Empty input buffer //fflush(stdin); //c language, no effect in vs //cin.sync(); //C + +, no effect in vs //cin. ignore(std::numeric_limits< streamsize >::max(), '\n');// Clears all the contents of the input buffer until a carriage return is encountered, and various compilers are valid //Custom clearBuff() clearBuff(); printf("Where is home?\n"); gets_s(addr);//At this time, use gets to encounter the carriage return character that is still in the buffer and throw it away printf("Please feel free to enter:"); char a[10]; gets_s(a); printf("name=%s,addr=%s,a=%s", name, addr,a); system("pause"); return EXIT_SUCCESS; }
Emptying the input buffer (four methods)
5. Practice
5.1 statistical words
1. Project requirements: allow to input multiple words, and count the number of words and the total length
2. Project realization:
C++
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <Windows.h> #include <string> #include <stdio.h> using namespace std; int main(void) { string word; int count = 0; int legth = 0; cout << "Please enter any number of words:" << endl; while (true) { //If the input is successful, the cin object itself will be returned. If the file terminator ctrl+z is encountered, 0 will be returned; The return value of cin > > in vs cannot be directly compared with 0; /* while(cin>>a)This is not the return value of cin, Instead, the > > operation overloads the function istream & operator > > (istream &, T &); The second parameter is determined by the type of CIN > > subsequent parameters. The return value type is istream & type. In most cases, the return value is cin itself (non-0 value). Only when EOF input is encountered, the return value is 0. However, in the compiler of vs2019, the return value of (CIN > > word) cannot be directly compared with 0. Logic is used here! */ if (!(cin >> word)) { break; } count++; legth += word.length(); } cout << "Altogether" << count << "Words" << endl; cout << "Total length:" << legth << endl; system("pause"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Windows.h> int main(void) { char word[64]; int count = 0; int length = 0; printf("Please enter any number of words:"); while (1) { // Input failed, return 0 // If the end of file character (ctrl+z) is encountered, return - 1 (EOF) if (!scanf("%s", word)) { break; } count++; length += strlen(word); } printf("Altogether%d Words\n", count); printf("Total length:%d\n", length); system("pause"); return 0; }
5.2 statistical lines
1. Project requirements: input multiple lines of words, and count the lines and the total length of words
2. Project realization:
C++
#include <iostream> #include <string> #include <Windows.h> using namespace std; int main030201(void) { string line; int lineCount = 0; int length = 0; cout << "Please enter any number of lines:" << endl; while (1) { // NULL (0) is returned when a file terminator is encountered if (!getline(cin, line)) { break; } lineCount++; length += line.length(); } cout << "Altogether" << lineCount << "that 's ok" << endl; cout << "Total length: " << length << endl; cout << "line = " << line << endl; system("pause"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #define true 1 #include <stdio.h> #include <stdlib.h> int main030202(void) { char line[255]; int lineCount = 0; int length = 0; printf("Please enter any line:\n"); while (true) { if (gets(line) == 0) // !gets(line) { break; } lineCount++; length += strlen(line); } printf("Total number of branches:%d\n", lineCount); printf("Total length:%d\n", length); system("pause"); return EXIT_SUCCESS; }