With strings, we have worked with you in almost every one of our program and to this lesson. More precisely with string constants – sequence of characters in double quotes. We often had to display certain information. For example:
The text in quotation marks is a string constant. Quotation marks are used to determine the beginning and end of a string constant and are not part of it.
Quite often necessary not only to print some short messages in the course of the program, but also to work with a certain text, store it somewhere, refer to it and edit, of necessity. The string constant, described above, we can not apply to the program, for example, in order, to overwrite it (we do not know her name or address in the memory). Now you will learn about one of the ways to work with strings in C ++. Later we will learn more with one way – using class string.
So the first: in C ++ for storing strings using character arrays. This is the same arrays, as we are already considered in the article about arrays in C ++, but they do not store numerical data, and character. You can imagine the characters of the array arranged in series in the adjacent memory cells – each cell holds one symbol and occupies one byte. One byte because, that each element in a character array is char type. The last character of each line is a symbol of \0 (null character). For example:
The text, including space, it consists of 11 characters. If the last cell is such . (point), not null character \0 – It is not the compiler string. And the work would have to be with this set of characters, as with a regular array – write to each cell separately and displayed character by character (using the loop):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); char str[12] = {'Ж','и','л','-','б','ы','л',' ','п','ё','с','.'}; for (int i = 0; i < 12; i++) { cout << str[i]; } cout << endl; return 0; } |
Fortunately, C ++ has a much more convenient way to initialize and access the character arrays – row. To do this, the last character of the array must be a null character \0. That it does set a string of characters, work with which, much easier, than with an array of characters.
Declares a string so – We create an array type char, Size in square brackets is optional (it calculates the compiler), operator = and quotation marks write the desired text. That is, we initialize an array of string constant:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); char str[] = "Жил-был пёс"; // '\0' присутствует неявно cout << str << endl; return 0; } |
Prescribing the null character is not necessary. It is implicit, and this is added to each string constant automatically. In this way, despite the fact that we see 11 characters per string, size of the array will be 12, as \0 also a symbol and occupies one byte of memory. He will take the last cell of the character array.
As you can see, for string output, enough to refer to it by name: cout << str << endl; cout it will display a character by character, until it encounters in one of the cells in an array of end-of-string character \0 and the output is interrupted. Such an appeal to the ordinary character array (array without \0) unacceptable.
Since the compiler to output characters to the screen, even going beyond the scope of the array, not yet met would at some memory location symbol \0. You can try to substitute the first instance, instead of the loop operatorcout << str << endl; and see, what happens. I have found here are so:
I wish to draw your attention to the difference of the character constant (in single quotes – 'f', '@' ) from a string constant (in double quotes "f", "@" ). For the first, C ++ compiler is allocated one byte to store in memory. For a character written in double quotes, two bytes of memory will be allocated – for the character and for the zero (added by the compiler).
What if the line will have to enter the user from the keyboard? In this case, you must declarearraychar with an indication of its size sufficient for storing input characters, including \0. Do not forget that a null character. If you need to store 3 character in the array, its size should be one more than the – ie 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); char siteName[20] = ""; cout << "Название сайта: "; cin >> siteName; cout << siteName << endl; return 0; } endl; |
Using empty quotes initialization, we assign a value to each element of the array \0. Thus the string will be cleared of “garbage” other programs. Even if the user enters the name contains fewer than the number of characters, following the name is a symbol \0. This will avoid unnecessary mistakes. In memory of this line would look like this:
By the way, if we assume overwrite the 11-th cell of the array – str[11] = ' ';
and an array of on-screen display, we see only purecodecpp despite, that in cells 12, 13, 14 remain stored characters. Null character will play a major role in bringing to the screen and all, that is behind it will not be shown.
Talk about putting strings with keyboard details. The thing is, that there are certain problems to be aware of and that you must learn to solve. The following program when entering the strings are not everything will be as smooth, as we want:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); char quote[128] = ""; cout << "Ваша любимая цитата из мультфильма \"Винни Пух\": "; cin >> quote; cout << quote << endl; return 0; } |
Do not bother is over, that entering through cin you want to produce in latin. About how to properly introduce the Cyrillic alphabet will be discussed in a separate article. Here you can see, that the quotation we have introduced, but the output to the screen, we see only the first word. This is because, that we can not enter null character from the keyboard, and cin perceives space, newline and tab, as the end of the string. That is, in this case cin i read only the first word, a comma and added automatically mark the end of the string. The other entered data placed in the input queue.
We solve this problem simply. In C ++ there is a functionget() and getline() , we can use together with cin. They are alike, but is more commonly usedgetline(). In this article, we will not consider the difference between them. Fill in our program inputgetline ():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); char quote[128] = ""; cout << "Ваша любимая цитата из мультфильма \"Винни Пух\": \n"; cin.getline(quote, 128); // передаем в функцию имя массива и его размер cout << quote << endl; return 0; } |
You see, that we have indicated in brackets for the two arguments function – in which an array of characters considered (array name) and the size of the array – string 11. The result suits us– all display the correct. cin.getline() It reads in an array of the entire line including spaces and tabs, unless there is a pressing Enter or until it exceeded the size of the array. A newstring character in the array will not be saved, and is replaced by a null character.
In C ++ string handling, there are many functions, which we will discuss in the next article. In it we talk about functions, that allow to overwrite strings, unite them, compared with each other, etc..
Share our articles with your friends on social networks – this is the best thanks. And if you have questions and suggestions – leave comments.
In addition to the read I recommend to watch the video tutorial:
Please tell me where can I find the moment missed in this article: “Do not bother is over, Please tell me where can I find the moment missed in this article. How to correctly enter the Cyrillic alphabet will be discussed in a separate article.” How to correctly enter the Cyrillic alphabet will be discussed in a separate article.?. How to correctly enter the Cyrillic alphabet will be discussed in a separate article.?
SetConsoleOutputCP(1251); // for withdrawal
SetConsoleCP(1251); // for input