The basics of programming in c++ for beginners

Strings in C ++, and character arrays

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:

строки в С++

Текст в кавычках и есть строковая константа. Кавычки используются для определения начала и конца строковой константы и её частью не являются.

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):

строки в С++, символьные массивы в С++

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:

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 и вывод прервется. Такое обращение для обычного символьного массива (array without \0) недопустимо.

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 – то есть 4.

строки в С++, символьные массивы в С++

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:

строки в С++, символьные массивы в С++

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 ():

строки в С++, символьные массивы в С++

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.

Дополнительно к прочитанному рекомендую посмотреть видео-урок:

24 thoughts on “Strings in C ++, and character arrays

  1. I do not understand – and how to write properly with the keyboard so large text – ” 'F', 'and', '', …. ” – and so on – I did one short word worn out writing – as well as just quoted!?

  2. В xcode не дает вводить русские буквы в массив, после объявления второго символа пишет, что места нет (Character too large for enclosing character literal type).
    Как можно исправить это?
    P.S. ваше видео недоступно, очень бы даже посмотрел его

  3. Найс, nearly 3 дня е###ся
    А тут просто шедевральный ответ

    char a[10] = “”;


Leave a Reply

Your email address will not be published. Required fields are marked *