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 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)
    #include
    using namespace std;
    int main()
    {
    char a[]={"abcefghi"};
    // переменная b - искомая точка в строке, начиная с которой делаем сдвиг
    // переменная с - добавляемый символ
    // переменная f - просто вспомогательная
    // sory за названия переменных нет времени возиться
    char b('c'), c('d'), f(' ');
    cout << a << endl;
    for ( int i=0; i<sizeof(a); i++)
    {
    if (a[i]==b)
    {
    b=c;
    f=a[i+1];
    a[i+1]=c;
    c=f;
    }
    }
    cout << a << endl;

    return 0;
    }

  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)


    #include
    #include

    using namespace std;

    struct Student
    {
    char fio[80];
    int number_group;
    int ball[5];
    };

    int main(int argc, char *argv[])
    {

    int count_students = 2;
    Student *stud = new Student[count_students];
    for (int i = 0; i < count_students; i++)
    {

    cout << endl << "Введите фамилию студента #" << i + 1 << ": ";
    cin.getline (stud[i].fio,80);
    cout << endl << "Введите номер группы студента #" << i + 1 <> stud[i].number_group;
    cout << endl << "Введите оценки студента #" << i + 1 << ": ";
    for (int j = 0; j > stud[i].ball[j];
    }
    }
    cout << endl;


      1. #include
        #include
        #include
        #include

        using namespace std;

        struct Student
        {
        char fio[80] = "";
        int number_group;
        int ball[5];
        };

        int main(int argc, char *argv[])
        {

        int count_students = 2;
        Student *stud = new Student[count_students];

        for (int i = 0; i < count_students; i++)
        {

        cout << endl << "Введите фамилию студента " << i + 1 << ": ";
        cin.getline (stud[i].fio,80);
        cout << endl << "Введите номер группы студента " << i + 1 <> stud[i].number_group;
        cout << endl << "Введите оценки (не более 5,через пробел) студента " << i + 1 << ": ";

        for (int j = 0; j > stud[i].ball[j];
        }

        }
        cout << endl;

        int count = 0;
        ofstream myfile;
        myfile.open ("C:/example.txt");
        for (int i = 0; i < count_students; i++)
        {

        for (int j = 0; j < 5;j++)
        {
        if ((stud[i].ball[j])== 2)
        {
        cout << stud[i].fio << " " << stud[i].number_group;

        myfile << stud[i].fio << " " << stud[i].number_group << "\t";

        cout << endl;
        count++;
        break;
        }
        }
        }
        myfile.close();
        if (count == 0)
        {
        cout << "Двоечников нет!";
        myfile.open ("C:/example.txt");
        myfile << "Двоечников нет!" << endl;
        myfile.close();
        }
        return 0;
        }

    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

    1. Absolutely wild intention!
      And you yourself would like to receive as a result of?: ‘A’*7 – how much is this?

  4. Find the product of an even number and the minimum, sostavlâûŝuû a-
    Thoroe number X how to solve this problem?

    1. First of all, in your problem formulation is not correct!
      What means “component number”? In mathematics, there is no concept sostavlyayushey.

      How are you, for example, imagine how should look like a solution for a particular value of X, let us say, X=113? Write.

      1. Then display, there is even a minimum number in the introduction of number

  5. Prompt, I do not understand why skipped 2nd prompted to enter the words?

    The console displays the following:

    Enter some words : word
    word
    Default char is: Y
    Enter new char: w
    The new symbol: w
    Thats It!!!
    2 Enter some words :
    3 Enter some words : word
    word
    Press any key to continue . . .

  6. as the value of the variable 32 Convert to the discharge line, for, then to divide it into 4 bytes?

    1. Something like this (details debug themselves):

      int32_t val = ...;
      char str[ 33 ] = " ", // 0 в позиции [32]
      hex[] = "0123456789ABCDEF"; // 16-тиричные символы
      for( int i = 0; i >= 4
      }
      cout << "строка: " << str << endl;

Leave a Reply

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