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:

строки в С++

Text in quotes is a string constant. Quotation marks are used to determine the beginning and end of a string constant, and it is often not.

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 and the output is interrupted. Such treatment for an 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 operator cout << 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 declare array char 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 – then there are 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 function get() and getline() , we can use together with cin. They are alike, but is more commonly used getline(). In this article, we will not consider the difference between them. Fill in our program input getline ():

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

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..

In addition to the read, it is desirable to see the video tutorial. Strings with 7 minutes:

Share our articles with your friends on social networks – this is the best thanks. And if you have questions and suggestions – leave comments.

Subscribe to notifications about new articles on our website:

Agree to receive notifications from to my e-mail

Strings in C ++, and character arrays

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

  1. I have a question. How can I iterate over the array, to find in it a symbol, and to add next to it is the same. For example the user enters D:\myfolder and the output should be D:\\myfolder\

    1. Watch the video. There inf, if chosen for an array of authors definition of array size[], that is the function sizeof, with the help of a cat can be in the for cycle through all the elements. for ( int i=0; i<sizeof(array); i ). Reached the target and insert. I think, so.

      1. This is not true:
        1. sizeof() returns occupied space array in bytes, for 10 element array char it will 10, and for the same array it will int 40.
        2. The array size can be defined as sizeof( array ) / sizeof( array[ 0 ] ). But this – Only in the array definition (before passing it somewhere function).
        3. The array can not be “insert” element, possible only if the piece push for all subsequent pending 1 to the right, but it's much too expensive.
        4. In string, Unlike array, You can insert an element.

  2. good afternoon. So I understand the question, The string must add symbol. (lesson topic because the string)

  3. why something is not working. Name the first student writes a variable, and the name of the second does not even enter (immediately jumps to the number groups)
    Prompt, what am I doing wrong)

    1. The thing is, that after the last data entry field stud structure[i].ball[j] symbol remains in the stream cin ' n'. That's it and reads the method getline(), without suspending the program, waiting for input.
      You need to add cin.get() the last team in the outer loop.

      Dmitry Belik

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>