Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: АрхеологияБиология Генетика География Информатика История Логика Маркетинг Математика Менеджмент Механика Педагогика Религия Социология Технологии Физика Философия Финансы Химия Экология ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Introducing the string Class↑ ⇐ ПредыдущаяСтр 6 из 6 Содержание книги Поиск на нашем сайте
The ISO/ANSI C++ Standard expanded the C++ library by adding a string class. So now, instead of using a character array to hold a string, you can use a type string variable (or object, to use C++ terminology). As you’ll see, the string class is simpler to use than the array and also provides a truer representation of a string as a type. To use the string class, a program has to include the string header file. The string class is part of the std namespace, so you have to provide a using directive or else refer to the class as std::string. The class definition hides the array nature of a string and lets you treat a string much like an ordinary variable. Listing 4 illustrates some of the similarities and differences between string objects and character arrays.
Listing 4 #include <iostream> #include <string> // make string class available void 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 }
Here is a sample run of the program in Listing 4: 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
You should learn from this example that in many ways, you can use a string object in the same manner as a character array: •You can initialize a string object to a C-style string. •You can use cin to store keyboard input in a string object. •You can use cout to display a string object. •You can use array notation to access individual characters stored in a string object. The main difference between string objects and character arrays shown in Listing 4 is that you declare a string object as a simple variable, not as an array:
string str1; // create an empty string object string str2 = “panther”; // create an initialized string
The class design allows the program to handle the sizing automatically. For instance, the declaration for str1 creates a string object of length zero, but the program automatically resizes str1 when it reads input into str1:
cin >> str1; // str1 resized to fit input
This makes using a string object both more convenient and safer than using an array. Conceptually, one thinks of an array of char as a collection of char storage units used to store a string but of a string class variable as a single entity representing the string.
Assignment, Concatenation, and Appending The string class makes some operations simpler than is the case for arrays. For example, you can’t simply assign one array to another. But you can assign one string object to another:
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 charr1 = charr2; // INVALID, no array assignment str1 = str2; // VALID, object assignment ok
The string class simplifies combining strings. You can use the + operator to add two string objects together and the += operator to tack on a string to the end of an existing string object. Continuing with the preceding code, we have the following possibilities:
string str3; str3 = str1 + str2; // assign str3 the joined strings str1 += str2; // add str2 to the end of str1
Listing 5 illustrates these usages. Note that you can add and append C-style strings as well as string objects to a string object.
Listing 5 #include <iostream> #include <string> // make string class available void 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; }
Recall that the escape sequence \” represents a double quotation mark that is used as a literal character rather than as marking the limits of a string.
Here is the output from the program in Listing 5: 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
More string Class Operations Even before the string class was added to C++, programmers needed to do things like assign strings. For C-style strings, they used functions from the C library for these tasks. The cstring header file (formerly string.h) supports these functions. For example, you can use the strcpy() function to copy a string to a character array, and you can use the strcat() function to append a string to a character array:
strcpy(charr1, charr2); // copy charr2 to charr1 strcat(charr1, charr2); // append contents of charr2 to char1
Working with string objects tends to be simpler than using the C string functions. This is especially true for more complex operations. For example, the library equivalent of
str3 = str1 + str2;
is this:
strcpy(charr3, charr1); strcat(charr3, charr2);
Furthermore, with arrays, there is always the danger of the destination array being too small to hold the information, as in this example:
char site[10] = “house”; strcat(site, “ of pancakes”); // memory problem
The strcat() function would attempt to copy all 12 characters into the site array, thus overrunning adjacent memory. This might cause the program to abort, or the program might continue running, but with corrupted data. The string class, with its automatic resizing as necessary, avoids this sort of problem. The C library does provide cousins to strcat() and strcpy(), called strncat() and strncpy(), that work more safely by taking a third argument to indicate the maximum allowed size of the target array, but using them adds another layer of complexity in writing programs. Notice the different syntax used to obtain the number of characters in a string:
int len1 = str1.size(); // obtain length of str1 int len2 = strlen(charr1); // obtain length of charr1
The strlen() function is a regular function that takes a C-style string as its argument and that returns the number of characters in the string. The size() function basically does the same thing, but the syntax for it is different. Instead of appearing as a function argument, str1 pre-cedes the function name and is connected to it with a dot. As you saw with the put() method, this syntax indicates that str1 is an object and that size() is a class method. A method is a function that can be invoked only by an object belonging to the same class as the method. In this particular case, str1 is a string object, and size() is a string method. In short, the C functions use a function argument to identify which string to use, and the C++ string class objects use the object name and the dot operator to indicate which string to use.
More on string Class I/O As you’ve seen, you can use cin with the >> operator to read a string object and cout with the >> operator to display a string object using the same syntax you use with a C-style string. But reading a line at a time instead of a word at time uses a different syntax. Listing 6 shows this difference.
Listing 6 #include <iostream> #include <string> // make string class available #include <cstring> // C-style string library void 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; }
Here’s a sample run of the program in Listing 6: Length of string in charr before input: 27 Length of string in str before input: 0 Enter a line of text: peanut butter You entered: peanut butter Enter another line of text: blueberry jam You entered: blueberry jam Length of string in charr after input: 13 Length of string in str after input: 13
This is the code for reading a line into an array:
cin.getline(charr, 20);
The dot notation indicates that the getline() function is a class method for the istream class. (Recall that cin is an istream object.) As mentioned earlier, the first argument indicates the destination array, and the second argument is the array size, which getline() used to avoid overrunning the array. This is the code for reading a line into a string object:
getline(cin,str);
There is no dot notation, which indicates that this getline() is not a class method. So it takes cin as an argument that tells it where to find the input. Also, there isn’t an argument for the size of the string because the string object automatically resizes to fit the string.
Lab Overview 2.1. Read the theory and answer Control Questions. 2.2. Develop the algorithm flowchart to solve a problem according to individual case from the Table below. 2.3. Write the program code according to the developed algorithm. 2.4. Debug the program, run it and make screenshots. 2.5. Prepare the Lab Report according to the required structure.
Report Structure - Title page - Task overview - Algorithm’s flowchart - Program code - Program running screenshots - Conclusions
Control Questions 4.1. What is a string? 4.2. What is ‘\0’ symbol? 4.3. How may we declare a string? 4.4. How to access string items? 4.5. How to read one word? 4.6. How to read a text line? 4.7. Describe the function getline. 4.8. Describe the function gets. 4.9. What is the class “string”? 4.10. Concatenation of strings. 4.11. Appending to a string.
References 5.1. Juan Soulié. C++ Language Tutorial. – 2007. – p. 60-62. 5.2. Sharam Hekmat. C++ Essentials. – PragSoft Corporation 2005. – p. 13-14. 5.3. Prata S. C++ Primer Plus (5th Edition). – Sams, 2004. – p. 114-130. Annex A Report’s Title Page
MINISTRY OF EDUCATION AND SCIENCE, YOUTH AND SPORT OF UKRAINE TERNOPIL NATIONAL ECONOMIC UNIVERSITY FACULTY OF COMPUTER INFORMATION TECHNOLOGIES AMERICAN-UKRAINIAN SCHOOL OF COMPUTER SCIENCE
REPORT on Lab#__ from discipline “Algorithmization and Programming” Topic: _______________________________________________
Performed by student of group CSUAP-11 _________________________________ Checked by Dr. Ihor Paliy
Ternopil – 2012
Підписано до друку 22.06.2012р. Формат 60х84/16. Папір офсетний. Друк на дублікаторі. Зам. № 6-1984 Умов.-друк. арк. 2,56. Обл.-вид. арк. 2,76. Тираж 50 прим.
Віддруковано ФО-П Шпак В.Б. Свідоцтво про державну реєстрацію: В02 № 924434 від 11.12.2006 р. Свідоцтво платника податку: Серія Е № 897220 м. Тернопіль, вул. Просвіти, 6 тел. 097 299 38 99, 063 300 86 72 E-mail: tooums@ukr.net
|
||||||||||||||||||||||||||||||||||||||||||||||
Последнее изменение этой страницы: 2016-04-18; просмотров: 201; Нарушение авторского права страницы; Мы поможем в написании вашей работы! infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.147.193.143 (0.009 с.) |