General characteristics c. Scanf C Function Description

This article discusses the scanf() function in general view without reference to a specific standard, therefore data from any C99, C11, C++11, C++14 standards are included here. Perhaps, in some standards, the function works with differences from the material presented in the article.

scanf C function - description

scanf() is a function located in the stdio.h(C) and cstdio(C++) header files, also known as formatted program input. scanf reads characters from the standard input stream (stdin) and converts them according to the format, then writes them to the specified variables. Format - means that the data is converted to a certain form upon receipt. So the scanf C function is described:

scanf("%format", &variable1[, &variable2,[…]]),

where variables are passed as addresses. The reason for this way of passing variables to a function is obvious: as a result of work, it returns a value indicating the presence of errors, so the only way to change the values ​​of variables is to pass by address. Also, thanks to this method, the function can process data of any type.

Some programmers refer to functions like scanf() or printf() as procedures because of the analogy with other languages.

Scanf allows you to input all the basic types of the language: char, int, float, string, etc. In the case of variables of type string, there is no need to specify the address sign - "&", since a variable of type string is an array, and its name is the address of the first element of the array in the computer's memory.

Input format or control string

Let's start by looking at an example of using the scanf C function from the description.

#include int main() ( int x; while (scanf("%d", &x) == 1) printf("%d\n", x); return 0; //requirement for linux systems )

The input format consists of the following four parameters: %[*][width][modifiers] type. In this case, the "%" sign and the type are mandatory parameters. That is, the minimum form of the format looks like this: “%s”, “%d” and so on.

In general, the characters that make up the format string are divided into:

  • format specifiers - everything that starts with the % character;
  • separator or space characters - they are space, tab (\t), new line (\n);
  • characters other than whitespace.

The function may not be safe.

Use the scanf_s() function instead of scanf().

(message from visual studio)

Type, or format specifiers, or conversion characters, or control characters

A scanf C declaration must contain, at a minimum, a format specifier, which is specified at the end of expressions beginning with a "%" sign. It tells the program the type of data to expect when entering, usually from the keyboard. List of all format specifiers in the table below.

Meaning

The program is waiting for a character input. The variable to be written must be of type char.

The program expects a decimal integer input. The variable must be of type int.

The program expects an input of a floating point (comma) number in exponential form. The variable must be of type float.

The program expects the input of a floating point number (comma). The variable must be of type float.

7

The program expects the input of a floating point number (comma). The variable must be of type float.

The program expects an octal number to be entered. The variable must be of type int.

The program is waiting for a string input. A string is a set of any characters up to the first separator character encountered. The variable must be of type string.

The program expects a hexadecimal number to be entered. The variable must be of type int.

The variable expects a pointer input. The variable must be of pointer type.

Writes to the variable an integer value equal to the number of characters read so far by the scanf function.

The program reads an unsigned integer. The variable type must be unsigned integer.

The program expects a binary number to be entered. The variable must be of type int.

The set of characters to be scanned. The program waits for input of characters, from the limited pool specified between scanf will work as long as there are characters from the specified set on the input stream.

Characters in the format string

Asterisk symbol (*)

The asterisk (*) is a flag indicating that the assignment operation should be suppressed. An asterisk is placed immediately after the "%" sign. For example,

Scanf("%d%*c%d", &x, &y); //ignore character between two integers. scanf("%s%*d%s", str, str2); //ignore integer between two strings.

That is, if you enter the line "45-20" in the console, the program will do the following:

  1. The variable "x" will be assigned the value 45.
  2. The variable "y" will be assigned the value 20.
  3. And the minus sign (dash) "-" will be ignored thanks to "%*c".

Width (or margin width)

This is an integer between the "%" sign and the format specifier that specifies maximum amount characters to read for the current read operation.

There are several important points to keep in mind:

  1. scanf will abort if it encounters a separator character, even if it didn't count 20 characters.
  2. If more than 20 characters are input, only the first 20 characters will be written to str.

Type modifiers (or precision)

These are special flags that modify the type of data expected for input. The flag is specified to the left of the type specifier:

  • L or l (small L) When "l" is used with the specifiers d, i, o, u, x, the flag tells the program that long int input is expected. When using "l" with the e or f specifier, the flag tells the program that it should expect a double value. The use of "L" tells the program that a long double is expected. The use of "l" with the "c" and "s" specifiers tells the program that two-byte characters like wchar_t are expected. For example, "%lc", "%ls", "%l".
  • h is a flag indicating the short type.
  • hh - indicates that the variable is a pointer to a value of type signed char or unsigned char. The flag can be used with the specifiers d, i, o, u, x, n.
  • ll (two small L's) indicates that the variable is a pointer to a value of type signed int or unsigned long long int. The flag is used with specifiers: d, i, o, u, x, n.
  • j - indicates that the variable is a pointer to the type intmax_t or uintmax_t from the header file stdint.h. Used with specifiers: d, i, o, u, x, n.
  • z - indicates that the variable is a pointer to the size_t type, the definition of which is in stddef.h. Used with specifiers: d, i, o, u, x, n.
  • t - indicates that the variable is a pointer to the ptrdiff_t type. The definition for this type is in stddef.h. Used with specifiers: d, i, o, u, x, n.

More clearly, the picture with modifiers can be presented in the form of a table. Such a description of scanf C for programmers will be clearer.

Other characters

Any characters encountered in the format will be discarded. It should be noted that the presence of whitespace or separator characters (newline, space, tab) in the control string can lead to different behavior of the function. In one version, scanf() will read without saving any number of separators until it encounters a character other than the separator, and in another version, spaces (only they) do not play a role and the expression "%d + %d" is equivalent to "% d+%d".

Examples

Let's consider a number of examples that allow you to think and more accurately understand the operation of the function.

scanf("%3s", str); //if you enter the string "1d2s3d1;3" in the console, only "1d2" will be written to str scanf("%dminus%d", &x, &y); //minus characters between two numbers will be discarded scanf("%5", str); // characters will be entered into str until there are 5 characters and the characters are numbers from 0 to 9. scanf("%lf", &d); //expect double input scanf("%hd", &x); //expected number of type short scanf("%hu", &y); //expect unsigned number short scanf("lx", &z); //expected number of type long int

From the examples given, you can see how the expected number changes using various characters.

scanf C - description for beginners

This section will be useful for beginners. Often you need to have on hand not so much Full description scanf C how many details of how the function works.

  • The feature is somewhat deprecated. There are several different implementations in the libraries various versions. For example, the improved scanf S C function, a description of which can be found on the microsoft.
  • The number of specifiers in the format must match the number of arguments passed to the function.
  • Elements of the input stream must be separated only by separator characters: space, tab, newline. Comma, semicolon, period, etc. - these characters are not separators for the scanf() function.
  • If scanf encounters a separator character, input will be stopped. If there is more than one variable to read, then scanf will move on to reading the next variable.
  • The slightest inconsistency in the format of the input data leads to unpredictable results of the program. Well, if the program just ends with an error. But often the program continues to work and does it wrong.
  • scanf("%20s...",...); If the input stream exceeds 20 characters, then scanf will read the first 20 characters and either abort or move on to reading the next variable, if one is specified. In this case, the next call to scanf will continue reading the input stream from the point where the work of the previous call to scanf stopped. If a separator character is encountered while reading the first 20 characters, scanf will abort or move on to reading the next variable, even if it did not read 20 characters for the first variable. In this case, all unread characters will be attached to the next variable.
  • If the set of scanned characters starts with a "^" sign, then scanf will read the data until it encounters a delimiter character or a character from the set. For example, "%[^A-E1-5]" will read data from the stream until one of the uppercase English characters from A to E or one of the numbers from 1 to 5 is encountered.
  • The scanf C function, by definition, returns a number equal to the number of successful writes to variables. If scanf writes 3 variables, then the success result of the function will return the number 3. If scanf could not write any variables, then the result will be 0. And, finally, if scanf could not start at all for some reason, the result will be EOF .
  • If the scanf() function completed its work incorrectly. For example, scanf("%d", &x) - a number was expected, but the input received characters. The next call to scanf() will start at the point in the input stream where the previous function call left off. To overcome this problem, it is necessary to get rid of the problem characters. This can be done, for example, by calling scanf("%*s"). That is, the function will read a string of characters and throw it away. In this tricky way, you can continue entering the necessary data.
  • Some implementations of scanf() do not allow "-" in the character set to be scanned.
  • The "%c" specifier reads each character from the stream. That is, it also reads the separator character. To skip the delimiter character and continue reading the desired character, "%1s" can be used.
  • When using the "c" specifier, it is acceptable to use the width "%10c", but then in the form function variable scanf needs to pass an array of elements of type char.
  • “%” means “all small letters of the English alphabet”, and “%” means just 3 characters: 'z', 'a', '-'. In other words, the character "-" means a range only if it is between two characters that are in the correct order. If "-" is at the end of an expression, at the beginning, or in the wrong order of characters on either side of them, then it is just a hyphen character, not a range.

Conclusion

This concludes the description of scanf C. This is a nice handy function to work with in small programs and when using the procedural method of programming. However, the main disadvantage is the number of unpredictable errors that can occur when using scanf. Therefore, the description of scanf C when programming is best kept in front of your eyes. In large professional projects, iostreams are used, due to the fact that they have higher-level capabilities, they are better able to catch and handle errors, as well as work with significant amounts of information. It should also be noted that the description of scanf C in Russian is available on many online sources, as well as examples of its use, due to the age of the function. Therefore, if necessary, you can always find the answer on thematic forums.

The C/C++ Standard Library includes a number of functions for reading and writing to the console (keyboard and monitor). These functions read and write data as a simple stream of characters.

The concept of a stream (stream), used in programming, is closely related to the usual, everyday understanding of this word. The input stream can be compared with a pipe through which water (information) enters the pool (computer memory), the output stream - with a pipe through which water leaves the pool. An important feature This pipe is that data can only move in one direction at a time. Even if the same pipe is used for inlet and outlet, it cannot happen at the same time: to switch the direction of the flow, you need to stop it, perform some action, and only then direct the flow in the opposite direction. Another feature of the stream is that it almost never dries up. Sometimes it dries up, but this period cannot be long if the system is functioning normally.

printf() standard output function

The printf() function is a standard output function. With this function, you can display a character string, a number, a variable value on the monitor screen ...

The printf() function has a prototype in the stdio.h file
int printf(char *control string, ...);

If successful, the printf() function returns the number of characters printed.

The control string contains two types of information: characters that are directly displayed on the screen, and format specifiers that determine how to output the arguments.

The printf() function is a formatted output function. This means that in the function parameters it is necessary to specify the format of the data to be output. The data format is specified by format specifiers. The format specifier begins with a % followed by a format code.

Format specifiers:

%With symbol
%d integer decimal number
%i integer decimal number
%e decimal number in the form x.xx e+xx
%E decimal number in the form x.xx E+xx
%f
%F decimal floating point xx.xxxx
%g %f or %e whichever is shorter
%G %F or %E whichever is shorter
%o octal number
%s character string
%u unsigned decimal number
%x hexadecimal number
%X hexadecimal number
%% symbol %
%p pointer
%n pointer

In addition, the l and h modifiers can be applied to format commands.

%ld print long int
%hu print short unsigned
%Lf print long double

In the format specifier, after the % symbol, the precision (the number of digits after the decimal point) can be specified. The precision is set as follows: %.n<код формата>. Where n is the number of digits after the decimal point, and<код формата>- one of the codes above.

For example, if we have a variable x=10.3563 of type float and we want to display its value with an accuracy of 3 decimal places, then we should write:

printf("Variable x = %.3f",x);

Result:
Variable x = 10.356

You can also specify the minimum width of the margin to be printed. If the string or number is greater than the specified field width, then the string or number is printed in full.

For example, if you write:

printf("%5d",20);

then the result will be:
20

Note that the number 20 was not printed from the very beginning of the line. If you want the unused places of the field to be filled with zeros, then you need to put the character 0 in front of the field width.

For example:

printf("%05d",20);

Result:
00020

In addition to data format specifiers, the control string can contain control characters:

\b BS, bottomhole
\f New page, page translation
\n New line, line feed
\r Carriage return
\t Horizontal tab
\v Vertical tab
\" double quote
\" Apostrophe
\\ Backslash
\0 Null character, null byte
\a Signal
\N Octal constant
\xN Hexadecimal constant
\? Question mark

Most often you will use the \n character. With this control character you will be able to jump to a new line. Look at the examples of programs and you will understand everything.

Program examples.

/* Example 1 */
#include

void main(void)
{
int a,b,c; // Announcement variables a,b,c
a=5;
b=6;
c=9;
printf("a=%d, b=%d, c=%d",a,b,c);
}

The result of the program:
a=5, b=6, c=9

/* Example 2 */
#include

void main(void)
{
float x,y,z;

X=10.5;
y=130.67;
z=54;

Printf("Object coordinates: x:%.2f, y:%.2f, z:%.2f", x, y, z);
}

The result of the program:
Object coordinates: x:10.50, y:130.67, z:54.00

/* Example 3 */
#include

void main()
{
intx;

X=5;
printf("x=%d", x*2);
}

The result of the program:
x=10

/* Example 4 */
#include

void main(void)
{
printf("\"Text in quotes\"");
printf("\nOxygen content: 100%%");
}

The result of the program:
"Text in quotation marks"
Oxygen content: 100%

/* Example 5 */
#include

void main(void)
{
int a;

A=11; // 11 in decimal equals b in hex
printf("a-dec=%d, a-hex=%X",a,a);
}

The result of the program:
a-dec=11, a-hex=b

/* Example 6 */
#include

void main(void)
{
char ch1,ch2,ch3;

Ch1="A";
ch2="B";
ch3="C";

Printf("%c%c%c",ch1,ch2,ch3);
}

The result of the program:
ABC

/* Example 7 */
#include

void main(void)
{
char *str="My string.";

Printf("This is %s",str);
}

The result of the program:
This is my line.

/* Example 8 */
#include

void main(void)
{
printf("Hello!\n"); // After printing, there will be a new line - \n
printf("My name is Paul."); // This will be printed on a new line
}

The result of the program:
Hello!
My name is Pavel.

scanf() standard input function

The scanf() function is a formatted input function. With it, you can enter data from the standard input device (keyboard). Inputs can be integers, floating point numbers, characters, strings, and pointers.

The scanf() function has the following prototype in stdio.h:
int scanf(char *control string);

The function returns the number of variables that have been assigned a value.

The control string contains three kinds of characters: format specifiers, spaces, and other characters. Format specifiers begin with the % character.

Format specifiers:

When entering a string using the scanf() function (format specifier %s), the string is entered up to the first space!! those. if you enter the string "Hello world!" using the scanf() function


scanf("%s",str);

then after entering the resulting string, which will be stored in the str array, will consist of one word "Hello". FUNCTION ENTERS A STRING UP TO THE FIRST SPACE! If you want to enter strings with spaces, then use the function

char *gets(char *buf);

With the gets() function, you can enter full strings. The gets() function reads characters from the keyboard until a character appears new line(\n). The newline character itself appears when you press the enter key. The function returns a pointer to buf. buf - buffer (memory) for the input string.

Although gets() is out of the scope of this article, let's write an example program that allows you to enter a whole line from the keyboard and display it on the screen.

#include

void main(void)
{
charbuffer; // array (buffer) for the input string

Gets(buffer); // enter a string and press enter
printf("%s",buffer); // output the entered string to the screen
}

Another important note! To enter data using the scanf() function, you need to pass the addresses of variables as parameters, and not the variables themselves. To get the address of a variable, precede the variable name with & (ampersand). The & sign means taking the address.

What does address mean? I'll try to explain. In the program we have a variable. A variable stores its value in computer memory. So the address that we get with & is the address in the computer's memory where the value of the variable is stored.

Let's look at an example program that shows us how to use &

#include

void main(void)
{
intx;

Printf("Enter variable x:");
scanf("%d",&x);
printf("Variable x=%d",x);
}

Now let's get back to the control line of the scanf() function. Again:

int scanf(char *control string);

The space character in the control line instructs to skip one or more spaces in the input stream. In addition to a space, a tab or newline character can be accepted. A non-null character indicates to read and discard that character.

The separators between two input numbers are space, tab, or newline characters. The * after the % and before the format code (format specifier) ​​instructs to read data of the specified type, but not to assign that value.

For example:

scanf("%d%*c%d",&i,&j);

typing 50+20 will set i to 50, j to 20, and the + will be read and ignored.

The format command can specify the largest field width to be read.

For example:

scanf("%5s",str);

specifies to read the first 5 characters from the input stream. If you enter 1234567890ABC, the str array will contain only 12345, the rest of the characters will be ignored. Separators: space, tab and newline - when entering a character, they are treated like all other characters.

If any other characters are encountered in the control string, they are intended to determine and skip the corresponding character. 10plus20 character stream by operator

scanf("%dplus%d",&x,&y);

will assign x to 10, y to 20, and skip the plus characters because they occur on the control line.

One of powerful features function scanf() is the ability to set the search set (scanset). The search set defines the set of characters against which characters read by scanf() will be compared. The scanf() function reads characters as long as they occur in the search set. Once the character that is entered is not found in the search set, the scanf() function moves on to the next format specifier. The search set is defined by a list of characters enclosed in square brackets. The opening parenthesis is preceded by a % sign. Let's look at this with an example.

#include

void main(void)
{
char str1, str2;
scanf("%%s", str1, str2);
printf("\n%s\n%s",str1,str2);
}
Let's enter a character set:
12345abcdefg456

On the screen, the program will display:
12345
abcdefg456

When specifying a search set, you can also use the hyphen character to specify spaces, as well as the maximum width of the input field.

scanf("%10", str1);

You can also define characters that are not in the search set. The first of these characters is preceded by a ^ sign. The character set distinguishes between lowercase and uppercase letters.

Let me remind you that when using the scanf () function, you need to pass the addresses of variables as parameters to it. Above code was written:

charstr; // array for 80 characters
scanf("%s",str);

Note that str is not preceded by &. This is because str is an array, and the name of the array, str, is a pointer to the first element of the array. Therefore, the & sign is not put. We are already passing the address to the scanf() function. Well, simply put, str is the address in computer memory where the value of the first element of the array will be stored.

Program examples.

Example 1
This program displays the query "How old are you?:" and waits for input. If, for example, you enter the number 20, the program will display the string "You are 20 years old.". When we called the scanf() function, we prefixed the age variable with an &, because the scanf() function needs the addresses of the variables. The scanf() function will write the entered value to the specified address. In our case, the entered value 20 will be written to the address of the age variable.

/* Example 1 */

#include

void main(void)
{
int age;

Printf("\nHow old are you?:");
scanf("%d",&age);
printf("You are %d years old.", age);
}

Example 2
Calculator program. This calculator can only add numbers. If you enter 100+34, the program will return the result: 100+34=134.

/* Example 2 */

#include

void main(void)
{
int x, y;

Printf("\nCalculator:");
scanf("%d+%d", &x, &y);
printf("\n%d+%d=%d", x, y, x+y);
}

Example 3
This example shows how to set the read field width. In our example, the field width is five characters. If you enter a string with more characters, then all characters after the 5th will be discarded. Pay attention to the scanf() function call. The & sign does not precede the name of the array name because the name of the array name is the address of the first element of the array.

/* Example 3 */

#include

void main(void)
{
charname;

Printf("\nEnter your username (maximum 5 characters):");
scanf("%5s", name);
printf("\nYou entered %s", name);
}

Example 4
The last example in this article shows how you can use the lookup set. After starting the program, enter a number from 2 to 5.

/* Example 4 */

#include

void main(void)
{
charbal;

Printf("Your score is 2,3,4,5:");
scanf("%", &bal);
printf("\nScore %c", bal);
}

C++ programming language

Last update: 08/28/2017

The C++ programming language is a general-purpose, high-level compiled programming language with static typing, which is suitable for creating a wide variety of applications. C++ is one of the most popular and widespread languages ​​today.

It has its roots in the C language, which was developed in 1969-1973 at Bell Labs by programmer Dennis Ritchie. In the early 1980s, Danish programmer Bjarne Stroustrup, then at Bell Labs, developed C++ as an extension to the C language. In fact, in the beginning, C++ simply supplemented the C language with some features of object-oriented programming. And so Stroustrup himself at first called it "C with classes" ("C with classes").

Subsequently new language began to gain popularity. New features were added to it that made it not just an addition to C, but a completely new programming language. As a result, "C with classes" was renamed to C++. And since then, both languages ​​began to develop independently of each other.

C++ is a powerful language, inheriting rich memory capabilities from C. Therefore, C++ often finds its application in system programming, in particular, when creating operating systems, drivers, various utilities, antiviruses, etc. By the way, Windows is mostly written in C++. But only system programming application given language is not limited. C++ can be used in programs of any level where speed and performance are important. It is often used to create graphic applications, various application programs. It is also especially often used to create games with rich rich visuals. In addition, the mobile direction has recently been gaining momentum, where C ++ has also found its application. And even in web development, you can also use C++ to create web applications or some kind of auxiliary services that serve web applications. In general, C++ is a widely used language in which you can write almost any kind of program.

C++ is a compiled language, which means that the compiler translates source in C++ into an executable file that contains a set of machine instructions. But different platforms have their own characteristics, so compiled programs cannot simply be transferred from one platform to another and run there. However, at the source code level, C++ programs are mostly portable unless some OS-specific features are used. And the availability of compilers, libraries, and development tools for almost all common platforms makes it possible to compile the same C++ source code into applications for these platforms.

Unlike C, the C++ language allows you to write applications in an object-oriented style, representing a program as a collection of classes and objects interacting with each other. This simplifies the creation of large applications.

Milestones of development

In 1979-80, Bjarne Stroustrup developed an extension to the C language - "C with classes". In 1983 the language was renamed to C++.

In 1985, the first commercial version of the C++ language was released, as well as the first edition of the book "The C++ Programming Language", which represented the first description of this language in the absence of an official standard.

Released in 1989 a new version C++ 2.0, which included a number of new features. After that, the language developed relatively slowly until 2011. But at the same time, in 1998, the first attempt was made to standardize the language by the ISO (International Organization for Standardization). The first standard was called ISO/IEC 14882:1998 or C++98 for short. Later in 2003 a new version of the C++03 standard was published.

In 2011, the new C++11 standard was published, which contained many additions and enriched the C++ language. a large number new functionality. This was followed in 2014 by a minor addition to the standard, also known as C++14. And another key release of the language is scheduled for 2017.

Compilers and Development Environments

To develop programs in C++, you need a compiler - it translates C++ source code into an executable file, which can then be run. But at the moment there are a lot of different compilers. They may differ in various aspects, in particular in the implementation of standards. A basic list of compilers for C++ can be found on wikipedia. It is recommended for development to choose those compilers that develop and implement all the latest standards. For example, throughout this tutorial, the freely available g++ compiler, developed by the GNU project, will be used predominantly.

You can also use IDEs such as Visual Studio, Netbeans, Eclipse, Qt, etc. to create programs.

Learning the basics and subtleties of the C++ programming language. Textbook with practical tasks and tests. Do you want to learn how to program? Then you are at the right place - here free education programming. Whether you have experience or not, these programming lessons will help you get started creating, compiling, and debugging C++ programs in different development environments: Visual Studio, Code::Blocks, Xcode, or Eclipse.

Lots of examples and detailed explanations. Perfect for both beginners (dummies) and more advanced. Everything is explained from scratch to the smallest detail. These lessons (200+) will give you a good base / foundation in understanding programming not only in C ++, but also in other programming languages. And it's absolutely free!

Also considered step by step creation c++ games, graphics library SFML and more than 50 tasks to test your skills and knowledge in C++. An added bonus is .

For repost +20 to karma and my gratitude!

Chapter number 0. Introduction. Beginning of work

Chapter number 1. Basics of C++

Chapter number 2. Variables and Basic Data Types in C++

Chapter number 3. Operators in C++

Chapter number 4. Scope and Other Types of Variables in C++

Chapter number 5. The order in which code is executed in a program. Loops, branches in C++

These tutorials are for everyone, whether you're new to programming or you already have extensive programming experience in other languages! This material is for those who want to learn the C / C ++ languages ​​from its very basics to the most complex structures.

C++ is a programming language, knowledge of this programming language will allow you to control your computer on highest level. Ideally, you can make the computer do whatever you want. Our site will help you learn the C++ programming language.

Installing /IDE

The very first thing you should do before you start learning C++ is to make sure you have an IDE - an integrated development environment (the program in which you will program). If you do not have an IDE, then you are here. When you decide on an IDE, install it and practice creating simple projects.

Introduction to C++

The C++ language is a set of commands that tell the computer what to do. This set of commands is usually called source code or just code. Commands are either "functions" or " keywords". Keywords (C/C++ reserved words) are the basic building blocks of the language. Functions are complex building blocks because they are written in terms of simpler functions, as you'll see in our very first program below. This structure of functions resembles the contents of a book. The table of contents can show the chapters of the book, each chapter in the book can have its own table of contents consisting of paragraphs, each paragraph can have its own subparagraphs. Although C++ provides many common functions and reserved words that you can use, there is still a need to write your own functions.

In what part of the program did you start? Each program in C++ has one function, it is called the main or main-function, the execution of the program begins with this function. From main function, you can also call any other functions, whether they are written by us or, as mentioned earlier, provided by the compiler.

So how do you access these Standard Functions? To access standard features that come with the compiler, you need to include the header file using the preprocessor directive — #include . Why is it effective? Let's look at an example work program:

#include << "Моя первая программа на С++\n"; cin.get(); }

Let's take a closer look at the elements of the program. #include is a "preprocessor" directive that tells the compiler to put the code from the iostream header file into our program before creating the executable. By including a header file in your program, you get access to many different functions that you can use in your program. For example, the cout statement requires an iostream . The line using namespace std; tells the compiler to use a group of functions that are part of the std standard library. This line also allows the program to use operators such as cout . The semicolon is part of the C++ syntax. It tells the compiler that this is the end of the command. You'll see a little later that the semicolon is used to terminate most commands in C++.

The next important line of the program is int main() . This line tells the compiler that there is a function named main , and that the function returns an integer of type int . Curly braces ( and ) signal the start ( and end ) of a function. Curly braces are also used in other blocks of code, but they always mean the same thing - the beginning and end of the block, respectively.

In C++, the cout object is used to display text (pronounced "cout"). He uses characters<< , известные как «оператор сдвига», чтобы указать, что отправляется к выводу на экран. Результатом вызова функции cout << является отображение текста на экране. Последовательность \n фактически рассматривается как единый символ, который обозначает новую строку (мы поговорим об этом позже более подробно). Символ \n перемещает курсор на экране на следующую строку. Опять же, обратите внимание на точку с запятой, её добавляют в конец, после каждого оператора С++.

The next command is cin.get() . This is another function call that reads data from the input data stream and waits for the ENTER key to be pressed. This command keeps the console window from closing until the ENTER key is pressed. This gives you time to look at the output of the program.

Upon reaching the end of the main function (the closing curly brace), our program will return the value 0 for the operating system. This return value is important because, by parsing it, the OS can judge whether our program completed successfully or not. A return value of 0 means success and is returned automatically (but only for the int data type, other functions require you to return the value manually), but if we wanted to return something else, like 1, we would have to do it manually.

#include using namespace std; int main() ( cout<<"Моя первая программа на С++\n"; cin.get(); return 1; }

To consolidate the material, type the program code in your IDE and run it. After the program has run and you've seen the output, experiment a bit with the cout statement. This will help you get used to the language.

Be sure to comment on your programs!

Add comments to the code to make it clearer not only for yourself but also for others. The compiler ignores comments when executing code, which allows any number of comments to be used to describe actual code. To create a comment use either // , which tells the compiler that the rest of the line is a comment, or /* followed by */ . When you're learning to program, it's useful to be able to comment on certain sections of code in order to see how the result of the program changes. You can read in detail about the commenting technique.

What to do with all these types of variables?

Sometimes it can be confusing to have multiple variable types when it seems like some variable types are redundant. It is very important to use the correct variable type, as some variables require more memory than others. Also, because of the way in which floating point numbers are stored in memory, the float and double data types are "imprecise" and should not be used when an exact integer value must be stored.

Declaring Variables in C++

To declare a variable, use the syntax type<имя>; . Here are some examples of variable declarations:

int num; character; float num_float;

It is allowed to declare several variables of the same type in one line, for this each of them must be separated by a comma.

int x, y, z, d;

If you've looked closely, you may have seen that a variable declaration is always followed by a semicolon. You can read more about the convention - "on naming variables".

Common Mistakes When Declaring Variables in C++

If you try to use a variable that is not declared, your program will not compile and you will get an error. In C++, all language keywords, all functions, and all variables are case sensitive.

Using Variables

So now you know how to declare a variable. Here is an example program demonstrating the use of a variable:

#include using namespace std; int main() ( int number; cout<< "Введите число: "; cin >>number; cin.ignore(); cout<< "Вы ввели: "<< number <<"\n"; cin.get(); }

Let's take a look at this program and study its code, line by line. The int keyword says that number is an integer. The cin >> function reads the value in number , the user must press enter after the entered number. cin.ignore() is a function that reads a character and ignores it. We have organized our input into the program, after entering a number, we press the ENTER key, the character which is also passed to the input stream. We don't need it, so we discard it. Keep in mind that the variable was declared to be of type integer, if the user tries to enter a decimal number it will be truncated (i.e. the decimal part of the number will be ignored). Try entering a decimal number or character sequence when you run the example program, the answer will depend on the input value.

Note that quote marks are not used when printing from a variable. The absence of quotes tells the compiler that there is a variable, and therefore that the program must check the variable's value in order to replace the variable's name with its value when executed. Multiple shift operators on the same line are perfectly acceptable and the output will be done in the same order. You must separate string literals (quoted strings) and variables, giving each a different shift operator<< . Попытка поставить две переменные вместе с одним оператором сдвига << выдаст сообщение об ошибке . Не забудьте поставить точку с запятой. Если вы забыли про точку с запятой, компилятор выдаст вам сообщение об ошибке при попытке скомпилировать программу.

Changing and comparing values

Of course, no matter what data type you use, variables are of little interest unless their value can be changed. The following shows some of the operators used in conjunction with variables:

  • * multiplication,
  • - subtraction,
  • + addition,
  • / division,
  • = assignment,
  • == equality,
  • > more
  • < меньше.
  • != not equal
  • >= greater than or equal
  • <= меньше или равно

Operators that perform mathematical functions must be used to the right of the assignment sign, in order to assign the result to the variable on the left.

Here are some examples:

A = 4 * 6; // use line comment and semicolon, a is 24 a = a + 5; // equals the sum of the original value and five a == 5 // not assigned five, check, and equal to 5 or not

You will often use == in constructs such as conditional statements and loops.

A< 5 // Проверка, a менее пяти? a >5 // Check if a is greater than five? a == 5 // Check if a is five? a != 5 // Check if a is not equal to five? a >= 5 // Check if a is greater than or equal to five? a<= 5 // Проверка, a меньше или равно пяти?

These examples do not show the use of comparison signs very clearly, but when we begin to study selection operators, you will understand why this is necessary.



Loading...
Top