Last Updated:

Strings and structures in C++

Strings in C++

String is a sequence (array) of characters. If a single character occurs in an expression, it must be enclosed in single quotation marks. When used in expressions, the string is enclosed in double quotation marks. The end-of-line feature is the null \0 character. In C++, you can describe strings by using a character array (an array of char elements) that provides a place to store the end-of-line feature.

For example, the description of a 25-character string should look like this:

1
char s[25];

Here, the s[24] element is used to store the end-of-line character.

1
char s[7] = "Hello";

You can also describe an array of strings:

1
char s[3][25] = {"Example""usage""strings"};

An array of 3 lines of 25 bytes each is defined.

To work with pointers, you can use (char *). The address of the first character will be the initial value of the pointer.

Consider an example of declaring and displaying strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL,«Rus»);
describe 3 lines, s3- char pointer
s2[20]*s3, s4[30];
cout<<"s2="; cin>>s2; enter the string s2
cout<<"s2="<<s2<<endl;
an entry in s3 of the address of the line where s4 is stored. Now the variables
(pointers) s3 and s4 store the value of the same address
s3 = s4;
cout<<"s3="; cin>>s3; entering the string s3
displays the strings s3 and s4, although the result is s3=s4;
now s3 and s4 are the same
cout<<"s3="<<s3<<endl;
cout<<«s4=»<<s4<<endl;
system(«pause»);
return 0
;
}

The result of the program:

But it should be noted that if the user enters words separated by a space in one variable, the program will work differently:

 

The thing is that the cin function enters strings before the space encountered. A more universal function is getline.

cin.getline(char *s, int n);

The function is intended for keyboard input of the string s with spaces, there should be no more than n characters in the string. Therefore, for the correct input of lines containing a space, it is necessary to replace cin>>s with cin.getline(s, 80) in our program.

Operations on strings

You can process a string as an array of characters by using array processing algorithms or by using special string-handling functions, some of which are listed below. To work with these strings, you must include the cstring library.

You can use the sprintf function from the stdio.h library to convert a number to a string.

Some functions of working with strings:

Function prototypeFunction Description
size_t strlen(const char *s)Calculates the length of the string s in bytes.
char *strcat(char *dest, const char *scr)attaches the src string to the end of the dest line, the resulting deadline is returned as the result
char *strcpy(char *dest, const char *scr)copies the scr string to the memory location that dest points to
char strncat(char *dest, const char *dest, size_t maxlen)attaches a string of maxlen characters of the src string to the end of the dest string
char *strncpy(char *dest, const char *scr, size_t maxlen)copies the maxlen characters of the src string to the memory location that dest points to
int ctrcmp(const char *s1, const char *s2)compares two strings in lexicographic order, taking into account the difference between uppercase and lowercase letters, the function returns 0 if the strings match, returns 1 if s1 is in alphabetically ordered order earlier than s2, and 1 in the opposite case.
int strncmp(const char *s1, const char *s2, size_t maxlen)compares the maxlen characters of two strings in lexicographic order, the function returns 0 if the strings match, returns 1 if s1 is in alphabetically ordered order earlier than s2, and 1 returns 1 in the opposite case.
double atof(const char *s)converts a string to a real number, if the conversion fails, the number 0 is returned
long atol(const char *s)converts a string to a long integer, if the conversion fails, 0 is returned
char *strchr(const char *s, int c);returns a pointer to the first occurrence of the character c in the string that s points to. if the c character is not found null is returned
char *strupr(char *s)converts the characters of the string that s points to to uppercase characters and then returns it

String data type

In addition to working with strings as an array of characters, C++ has a special string data type. To enter variables of this type, you can use cin, or the special function getline.

getline(cin, s);

Where s is the name of the variable of type string that you are entering.

When you describe a variable of this type, you can immediately assign a value to that variable.

string var(s);

Here var is the name of the variable, s is the string constant. This statement creates a variable var of type string and writes the value of the string constant s to it. For example

string v(«Hello»);

A string v is created and the Hello value is written to it.

The i-th element of a string of type s is accessed in the standard way s[i]. The following operations are defined above string strings:

  • Assignments, such as s1=s2.
  • string concatenation (s1+=s2 or s1=s1+s2) — adds the string s2 to the line s1, the result is stored in the string s1, an example of string concatenation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
setlocale(LC_ALL,«Rus»);
string a,b;
cout<<"a="; getline(cin, a);
cout<<"b="; getline(cin, b);
a+=b;
cout<<"a="<<a<<endl;
system(«pause»);
return 0
;
}
  • string comparisons based on lexicographic order: s1=s2, s1!=s2, s1<s2, s1>s2, s1<=s2, s1>=s2 — the result will be a boolean value;

When processing string strings, you can use the following functions:

  • s.substr(pos, length) — returns a substring from the string s, starting with the pos number of the long length characters;
  • s.empty() - returns true if the string s is empty, false - otherwise;
  • s.insert(pos, s1) — inserts the string s1 into the line s, starting at the pos position;
  • s.remove(pos, length) — removes the length substring of long pos characters from the string s;
  • s.find(s1, pos) — returns the number of the first occurrence of the string s1 in the string s, the search begins with the pos number, the pos parameter may be missing, in this case the search goes from the beginning of the line;
  • s.findfirst(s1, pos) — returns the number of the first occurrence of any character from the string s1 to the string s, the search begins with the pos number, which may be missing.

strings

 

I think you have already noticed that when displaying Russian letters, "left" symbols appear in the console. In order to avoid this misunderstanding, it is necessary to use the third-party function CharToOemA. We connect the windows.h library, it is needed so that our function can convert strings to another encoding. Also, we will need an additional character array. The source code of the program will look like this:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{setlocale(LC_ALL,«Rus»);
char s[255]={" I need to convert "};
char *pre=new char[255];
CharToOemA(s, pre); convert
cout<<s;
delete []pre;
system(«pause>>void»);
return 0
;
}

The method just described is not convenient enough. But there is a simpler solution to the "Russian" problem. As you can see, the program uses the setlocale() function, instead it is more convenient to write the following construct into the main function:

1
2
3
4
5
6
7
8
9
10
11
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
system(«pause>>void»);
return 0
;
}

Now we have the windows.h library, as well as two new functions: SetConsoleCP() and SetConsoleOutputCP().

Structures in C++

 

In addition to numeric and symbolic data, C++ has a type that allows you to combine heterogeneous data and process it as a single unit. This type is called structure. A structure is a collection of one or more objects (variables, arrays, pointers, etc.) that are combined under a single name for ease of working with them.

Defining the structure consists of two steps:

  • Declaring a structure (specifying a new user-defined data type) the structure consists of fields, for example:
1
2
3
4
5
6
7
8
9
10
11
12
struct student
{
define the structure fields:
fio
char fio field[30];
group
char group field[8];
year
field int year;
fields informatika, math, fizika, history
int informatika, math, fizika, history
;
}
  • definition of variables of the "structure" type:
1
2
3
defined a Vasya variable of type student and an array ES[50], whose elements
are of type student, pointer x to data type student.
student Vasya, ES[50]*x
;

To access the fields of the structure, you need to specify the name of the variable and, through a period, the name of the field

Structura.pole

When working with dynamic arrays of structures, their fields can be accessed in a different way. The reference to the year field of the i-th element of the dynamic array of the structure x can be written as follows:

(x+i)->year;