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:

строки в С++

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

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

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

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

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.

In addition to the read I recommend to watch the video tutorial:

29 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. In xcode does not enter Russian letters in the array, after the second character writes ad, that there is no place (Character too large for enclosing character literal type).
    How can I fix it?
    P.S. Your video is not available, I would very much even looked it up

  3. Nice, nearly 3 ie ### days camping
    And then just a masterpiece answer

    char a[10] = “”;

    cin.getline(a,10);

  4. wires, great article. but there is a question. when I count the number of digits in a line it displays me 0. prompt. what am I doing wrong? here is the code:
    char text[] = “1 lame pull23 billowy beds person90 close vie13 well – groomed 47madly believe abaft meek35 probable 5familiar 12spotty elderly blue – eyed scare “;
    cout <<"ви працюєте з цим текстом:"<<endl<< text<<endl;
    //1

    int k = strlen(text);//count the number of characters
    cout << k<<endl;
    int counter = 0;
    for (int i = 0; i < k; i ) {

    if (isdigit(i) == true) {//here it should determine where the number is and if there is a number
    counter++; // then the counter should increase by 1
    }

    }
    cout << counter;
    }

    1. if (isdigit(text[i]))
      {//here it should determine where the number is and if there is a number
      counter++; // then the counter should increase by 1
      }

  5. Hello, please help with the code, i need everyone 5 replace the element with the letter x
    #include
    #include
    using namespace std;
    int main() {
    setlocale(LC_ALL, “Russian”);
    double n, S = 0;
    int a[100];
    int i;
    cout << "Выполнила: Art. groups n nJob: Everyone 5 replace element with letter x n nEnter the number of elements: " <> n;
    cout << endl;
    cout << "Введите " << n << " elements: " << endl;
    for (i = 0; i > a[i];
    if (a[i] < 0) {
    S = S + a[i];
    }
    }
    cout << endl << "Массив: " << endl;
    for (i = 0; i < n; i ) {
    cout << setw(4) << a[i];
    }
    cout << endl;
    cout << endl << "Сумма отрицательных элементов S=" << S << endl;
    char x;
    cout << endl << "Введите букву x" <> x;
    for (char i = 4; i < n; i=i+5) {
    a[i] = x;
    }
    cout << endl << "Измененный массив: everyone 5 replace element with letter x " << endl;
    for (i = 0; i < n; i ) {
    cout << setw(4) << a[i];
    }
    cout << endl;
    return 0;
    }
    What do I need to change here?

Leave a Reply

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