What is the C language? Scanf C function: description

What is the C language? Scanf C function: description

15.10.2023

C++ (read c-plus-plus) is a compiled, statically typed general-purpose programming language in which you can create programs of any level of complexity.
For more than 20 years, this language has been among the three most popular and in-demand programming languages. (You can verify this by visiting the TIOBE website).
The language originated in the early 1980s, when Bell Labs employee Björn Stroustrup came up with a number of improvements to the C language for his own needs.

Bjarne Stroustrup – creator of the C++ language

Stroustrup decided to extend the C language with the capabilities found in the Simula language. C, being the base language of the UNIX system on which Bell computers ran, is fast, feature-rich, and portable. Stroustrup added the ability to work with classes and objects. As a result, practical modeling problems turned out to be easy to solve both in terms of development time (thanks to the use of Simula-like classes) and in terms of computation time (thanks to the speed of C).
Here's how the language developer himself talks about it:



In 1998, the first language standard, known as C++98, was published by a standards committee. C++ continues to evolve to meet today's demands. One of the groups developing the C++ language and submitting proposals for improving it to the C++ Standards Committee is Boost, which is engaged, among other things, in improving the capabilities of the language by adding metaprogramming features to it. The latest standard was released in 2017 and is called C++17. The next standard will not be long in coming and is expected to appear in 2020.
Nobody owns the rights to the C++ language; it is free. In March 2016, a working group WP21 C++ was created in Russia. The group was organized to collect proposals for the C++ standard, send them to a committee and defend them at general meetings of the International Organization for Standardization.
C++ is a multi-paradigm language (from the word paradigm - a style of writing computer programs), including a wide range of different programming styles and technologies. It is often classified as an object-oriented language, but strictly speaking, this is not the case. During the work process, the developer receives absolute freedom in choosing tools so that the problem solved using a particular approach is solved as efficiently as possible. In other words, C++ does not force the programmer to adhere to only one style of program development (for example, object-oriented).
C++ has a rich standard library that includes common containers and algorithms, I/O, regular expressions, multithreading support, and other features. C++ has influenced many programming languages, including: Java, C#, D. Since C++ belongs to a family of languages ​​based on the syntax of the C language, you can easily master other programming languages ​​of this family: JavaScript, PHP, Perl, Objective-C and many others . etc., including the parent language itself - C. ()
During its existence, the C++ language has acquired persistent myths that are easily refuted (see here: Part 1 and Part 2)

History of the language and standards release

1983

The creator of the language is Björn Stroustrup, a Bell Labs employee, introduced an early version of the C++ language (“C with classes”)

1985

First commercial release of C++, the language takes on its modern name

1986

Release of the first edition of The C++ Programming Language - a book dedicated to C++ written by Björn Stroustrup

1998

The international standard for the C++ language has been ratified: ISO/IEC 14882:1998 “Standard for the C++ Programming Language”

2003
2005

Library Technical Report 1 (TR1) has been released. While not officially part of the standard, the report described extensions to the standard library that should be included in the next version of the C++ language.

2011

Release of a new standard – C++11 or ISO/IEC 14882:2011; the new standard included additions to the language core and expansion of the standard library, including most of TR1

2014

Release of the C++14 standard (“International Standard ISO/IEC 14882:2014(E) Programming Language C++”); C++14 can be seen as a small extension over C++11, containing mostly bug fixes and minor improvements

2017

The release of a new standard – C++1z (C++17). This standard introduced many changes and additions. For example, STD included libraries of the C11 standard, a file system based on boost::filesystem, and most of the experimental TS I library.

2020

C++20 is the unofficial name of the ISO/IEC standard for the C++ programming language, which is expected to follow C++17. Draft N4800 standard.

C++ Philosophy

In his book The Design and Evolution of C++ (2007), Björn Stroustrup describes the principles he followed when designing C++ (abbreviated):

  • Get a general-purpose language with static data types, the efficiency and portability of the C language.
  • Directly and comprehensively support a variety of programming styles.
  • Give the programmer freedom of choice, even if it gives him the opportunity to choose wrongly.
  • Maintain compatibility with C as much as possible, thereby making an easy transition from C programming possible.
  • Avoid discrepancies between C and C++: any construct that is valid in both languages ​​must mean the same thing in each of them and lead to the same program behavior.
  • Avoid features that are platform dependent or not universal.
  • “Don't pay for what you don't use” - no language feature should lead to a decrease in the performance of programs that do not use it.
  • Do not require an overly complicated programming environment.

C and C++

The syntax of C++ is inherited from the C language. Although, formally, one of the principles of C++ remains maintaining compatibility with the C language, in fact, the standardization groups for these languages ​​do not interact, and the changes they make not only do not correlate, but often fundamentally contradict each other ideologically. Thus, the elements that the new C standards add to the kernel are in the C++ standard elements of the standard library and are not in the kernel at all, for example, dynamic arrays, arrays with fixed boundaries, parallel processing facilities. According to Stroustrup, combining the development of these two languages ​​would be of great benefit, but it is unlikely to be possible for political reasons. So practical compatibility between C and C++ will gradually be lost.
In this example, depending on the compiler used, either “C++” or “C” will be output:

Program 9.1

#include int main() ( printf("%s\n", (sizeof("a") == sizeof(char)) ? "C++" : "C"); return 0; )

This is due to the fact that character constants in C are of type int , and in C++ they are of type char , but the sizes of these types are different.

Application Lifecycle Models

Life cycle software is a period of time that begins from the moment a decision is made on the need to create a software product and ends at the moment it is completely removed from service. This cycle is the process of building and developing software. There are several life cycle models.
Cascade model life cycle (English waterfall model) was proposed in 1970 by Winston Royce. It provides for the sequential implementation of all stages of the project in a strictly fixed order. The transition to the next stage means the complete completion of work at the previous stage. The requirements determined at the stage of requirements formation are strictly documented in the form of technical specifications and are recorded for the entire development of the project. Each stage culminates in the release of a complete set of documentation sufficient to allow development to be continued by another development team.
Project stages according to the waterfall model:

  1. Formation of requirements;
  2. Design;
  3. Implementation;
  4. Testing;
  5. Implementation;
  6. Operation and maintenance.

In the cascade model, the transition from one project phase to another assumes that the result of the previous phase is completely correct. In large projects this is almost impossible to achieve. Therefore, this model is only suitable for developing a small project. (W. Royce himself did not adhere to this model and used an iterative model).
Iterative model
An alternative to the cascade model is the iterative and incremental development (IID) model, which received from T. Gilb in the 70s. name of the evolutionary model. The IID model involves breaking the project life cycle into a sequence of iterations, each of which resembles a “mini-project”, including all development processes applied to the creation of smaller pieces of functionality compared to the project as a whole. The goal of each iteration is to obtain a working version of the software system, including functionality defined by the integrated content of all previous and current iterations. The result of the final iteration contains all the required functionality of the product. Thus, with the completion of each iteration, the product receives an increment - an increment - to its capabilities, which, therefore, develop evolutionarily.


Various variants of the iterative approach are implemented in most modern development methodologies:

Development Process - Rational Unified Process (RUP)

Rational Unified Process (RUP)(rational unified process) is a software development methodology maintained by Rational Software (IBM). The methodology provides recommendations for all stages of development: from business modeling to testing and commissioning of the finished program. The Unified Modeling Language (UML) is used as a modeling language.
The complete product development life cycle consists of four phases, each of which includes one or more iterations.

  • Initial stage (Inception)
  • Determining the scope of the project and the amount of resources required. The basic requirements, limitations and key functionality of the product are determined. Risks are assessed. Action planning. At the end of the initial phase, the achievement of the Lifecycle Objective Milestone is assessed, which presupposes an agreement between stakeholders to continue the project.

  • Clarification
  • Documenting requirements. Design, implementation and testing of executable architecture. Clarification of terms and costs. Reducing key risks. Successful completion of the development phase means reaching the Lifecycle Architecture Milestone.

  • Construction
  • In the “Build” phase, most of the product’s functionality is implemented: the application design is completed, the source code is written. The Build phase ends with the first external release of the system and the Initial Operational Capability milestone.

  • Introduction
  • In the “Implementation” phase, the final version of the product is created and transferred from the developer to the customer. This includes a beta testing program, user training, and determining the quality of the product. In case the quality does not meet user expectations or the criteria set in the Start phase, the Implementation phase is repeated again. Completing all goals means achieving the Product Release milestone and completing the full development cycle.



"Information technology. System and software engineering. Software life cycle processes". This standard was adopted by the Federal Agency for Technical Regulation and Metrology of the Russian Federation and is similar to the international standard ISO/IEC 12207:2008. This standard establishes a general structure of software life cycle processes that can be followed in the software industry. The standard does not propose a specific life cycle model. Its provisions are common to any life cycle models, methods and technologies for software creation. It describes the structure of life cycle processes without specifying how to implement or complete the activities and tasks included in those processes.

Presentation for the lesson
Message topics
  • Free Software Foundation (FSF)
  • Free software licenses
  • FreeSoftware and Open Source
  • History of the development of programming languages
  • The history of the C language. C and C++
  • Story
  • Criticism of C++
  • History of UNIX
  • Spiral software life cycle model
  • UML (Unified Modeling Language)
  • Microsoft Solutions Framework
  • IDE for C/C++ programming on Windows
  • C/C++ compilers
  • Creating a Console Application on Windows
Questions
  1. Why is the waterfall model of software development not used in large projects?
  2. What is the difference between waterfall and iterative development models?
  3. List the stages of software development in the Rational Unified Process (RUP) methodology

1. Introduction

Programming requires new universal algorithmic models, and hardware implements algorithms not only in a different form, but also on the basis of a different algorithmic model - automata. Borrowing technology from hardware development is the key idea behind automata programming. However, digital device synthesis is different from programming. But when borrowing a model, on the one hand, it is not advisable to change it significantly, and, on the other hand, one cannot ignore the already existing theory and practice of programming.

Next, we will look at the SWITCH technology for designing automata programs, in which you encounter similar processes all the time. On the one hand, it changed the finite state machine model so much that it actually took it beyond the scope of automata theory. And, on the other hand, it introduces concepts into programming that are difficult for programmers to perceive, and, at times, are simply superfluous, because there are more familiar analogues from program theory and programming practice.

As a basis for discussing the problems of automatic programming, we will take the recent lecture by Shalyto A.A. and his “programming” articles towards the definition of the automatic programming paradigm.

These tutorials are for everyone, whether you're new to programming or 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 at the highest level. Ideally, you will be able to make the computer do whatever you want. Our site will help you master the C++ programming language.

Installation /IDE

The very first thing you should do before you start learning C++ is to make sure that you have an IDE - an integrated development environment (the program in which you will program). If you don't have an IDE, then here you go. Once you decide on the choice of 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 simply 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 - you'll see this in our very first program, which is shown below. This structure of functions resembles the contents of a book. The content can show the chapters of the book, each chapter in the book can have its own content 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.

What part of the program does it start at? Each program in C++ has one function, it is called the main or main function, program execution begins with this function. From the main function, you can also call any other functions, whether they are ones we wrote or, as mentioned earlier, provided by the compiler.

So how do you access these Standard Features? To access the standard functions that come with the compiler, you need to include the header file using the preprocessor directive - #include . Why is this effective? Let's look at an example of a working program:

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

Let us consider in detail 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 connecting a header file to a program, you get access to many different functions that you can use in your program. For example, the cout operator requires iostream . 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 C++ syntax. It tells the compiler that this is the end of the command. You'll see in a moment that semicolons are 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 called main and that the function returns an integer. Curly braces ( and ) signal the start (and end) of a function. Curly braces are also used in other blocks of code, but they always indicate one thing - the beginning and end of the block, respectively.

In C++, the cout object is used to display text (pronounced "C out"). He uses symbols<< , известные как «оператор сдвига», чтобы указать, что отправляется к выводу на экран. Результатом вызова функции 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 see the output of the program.

Upon reaching the end of the main function (the closing curly brace), our program will return the value 0 to the operating system. This return value is important because by analyzing 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 manually return the value), but if we wanted to return something else, such as 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 into your IDE and run it. Once the program has run and you've seen the output, experiment a little with the cout statement. This will help you get used to the language.

Be sure to comment on your programs!

Add comments to your code to make it clearer not only for yourself but also for others. The compiler ignores comments when executing code, allowing you to use any number of comments to describe the actual code. To create a comment, use or // , which tells the compiler that the rest of the line is a comment, or /* and then */ . When you're learning to program, it's useful to be able to comment on parts of the code to see how the output 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 some variable types seem to be redundant. It is very important to use the correct variable type, as some variables require more memory than others. Additionally, due to the way they are stored in memory, floating point numbers, the float and double data types are "imprecise" and should not be used when a precise integer value needs to be stored.

Declaring Variables in C++

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

Int num; char character; float num_float;

It is permissible to declare several variables of the same type on one line; to do 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 learn 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 receive an error message. 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 examine its code, line by line. The keyword int indicates that number is an integer. The cin >> function reads the value into 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, a symbol that is also transmitted to the input stream. We don't need it, so we discard it. Keep in mind that the variable was declared as an integer type, if the user tries to enter a decimal number, it will be truncated (that is, the decimal part of the number will be ignored). Try entering a decimal number or a sequence of characters, when you run the example program, the answer will depend on the input value.

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

Changing and comparing values

Of course, no matter what type of data you're using, variables aren't very interesting without the ability to change their value. The following shows some operators used in conjunction with variables:

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

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 equal to 24 a = a + 5; // equal to the sum of the original value and five a == 5 // does not assign five, checks whether it is equal to 5 or not

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

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

These examples don't show the use of comparison signs very clearly, but when we start studying selection operators, you'll understand why this is necessary.

This article discusses the scanf() function in a general way without reference to a specific standard, so data from any C99, C11, C++11, C++14 standards is included here. It is possible that in some standards the function works differently from the material presented in the article.

scanf C function - description

scanf() is a function located in the header file of stdio.h(C) and cstdio(C++), it is also called formatted input to the program. scanf reads characters from standard input (stdin) and converts them according to the format, then writes them to the specified variables. Format means that the data, when received, is reduced to a certain form. Thus, the scanf C function is described:

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

where variables are passed as addresses. The reason for passing variables to a function this way is obvious: as a result of its operation, 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 call functions like scanf() or printf() procedures because of analogies with other languages.

Scanf allows you to enter all basic language types: char, int, float, string, etc. In the case of variables of type string, there is no need to indicate 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 computer memory.

Data 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 type are required parameters. That is, the minimum format looks like this: “%s”, “%d” and so on.

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

  • format specifiers - everything that begins with the % symbol;
  • separating or whitespace characters - these are space, tab (\t), new line (\n);
  • characters other than whitespace.

The function may be unsafe.

Use scanf_s() instead of scanf().

(posted by Visual Studio)

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

The description of scanf C must contain, at a minimum, a format specifier, which is indicated at the end of expressions beginning with the "%" sign. It tells the program the type of data to expect upon input, usually from the keyboard. A list of all format specifiers is in the table below.

Meaning

The program waits for a character to be entered. The variable to be written must be of character type char.

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

The program expects a floating point number in exponential form. The variable must be of type float.

The program expects a floating point number to be entered. The variable must be of type float.

7

The program expects a floating point number to be entered. 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 expects a string to be entered. A string is considered to be a set of any characters up to the first delimiter 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 a pointer type.

Writes an integer value to a variable 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.

A set of scannable characters. The program waits for input of characters from a limited pool specified between scanf and will work as long as there are characters from the specified set on the input stream.

Characters in the format string

Asterisk (*)

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 the character between two integers. scanf("%s%*d%s", str, str2); //ignore the 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 field width)

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

There are a few important points to keep in mind:

  1. scanf will stop running if it encounters a delimiter character, even if it hasn't counted 20 characters.
  2. If the input contains more than 20 characters, only the first 20 of them will be written to the str variable.

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

The picture with modifiers can be more clearly presented in the form of a table. This description of scanf C will be clearer for programmers.

Other characters

Any characters encountered in the format will be discarded. It is worth noting that the presence of whitespace or delimiting 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 delimiters until it encounters a character other than the delimiter, and in another version, spaces (only they) do not matter and the expression "%d + %d" is equivalent to "% d+%d".

Examples

Let's look at a number of examples to help you think about and more accurately understand how the function works.

Scanf("%3s", str); //if you enter the line “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 of them and the characters are numbers from 0 to 9. scanf("%lf", &d); //expected input of type double scanf("%hd", &x); //expect a number of type short scanf("%hu", &y); //expect a number of type unsigned short scanf("lx", &z); //expected number of type long int

From the examples given you can see how the expected number changes using different symbols.

scanf C - description for beginners

This section will be useful for beginners. Often you need to have on hand not so much a complete description of scanf C, but rather the details of how the function works.

  • The function is somewhat obsolete. There are several different implementations in libraries of different versions. For example, the improved scanf S C function, a description of which can be found on the Microsoft website.
  • The number of specifiers in the format must correspond to the number of arguments passed to the function.
  • Elements of the input stream must be separated only by delimiting characters: space, tab, newline. Comma, semicolon, period, etc. - these characters are not delimiters for the scanf() function.
  • If scanf encounters a delimiter character, input will be stopped. If there is more than one variable to read, scanf will move on to reading the next variable.
  • The slightest discrepancy in the format of the input data leads to unpredictable results from the program. It's good if the program just ends with an error. But often the program continues to work and does it incorrectly.
  • scanf("%20s ...", ...); If the input stream exceeds 20 characters, scanf will read the first 20 characters and either terminate or move on to read the next variable, if specified. The next scanf call will continue reading the input stream from where the previous scanf call left off. If a delimiter character is encountered while reading the first 20 characters, scanf will stop running or move on to reading the next variable, even if it did not read 20 characters for the first variable. In this case, all uncounted characters will be attached to the next variable.
  • If the set of characters to be scanned begins with the "^" 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 A through E or one of the numbers 1 through 5 is encountered.
  • The scanf C function, as described, returns a number equal to the successful number of entries into variables. If scanf writes 3 variables, then the result of the successful operation of the function will be the return of the number 3. If scanf could not write any variables, then the result will be 0. And finally, if scanf could not start working at all for some reason, the result will be EOF .
  • If the scanf() function did not complete its work correctly. For example, scanf("%d", &x) - a number was expected, but symbols were received as input. The next scanf() call will start from the point in the input stream where the previous function call ended. To overcome this problem, you need to get rid of the problematic 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 clever way, you can continue entering the required data.
  • Some implementations of scanf() do not allow the use of "-" in the character set to be scanned.
  • The “%c” specifier reads each character from the stream. That is, it also reads the delimiter character. To skip the delimiter character and continue reading the desired character, you can use “%1s”.
  • When using the “c” specifier, it is acceptable to use the width “%10c”, but then you must pass an array of elements of type char as a variable to the scanf function.
  • “%” means “all small letters of the English alphabet”, and “%” simply means 3 characters: ‘z’, ‘a’, ‘-’. In other words, the "-" character only means a range if it appears 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 it, then it simply represents a hyphen character, not a range.

Conclusion

This concludes the description of scanf C. It is a good convenience function for working in small programs and when using a procedural method of programming. However, the main drawback is the number of unpredictable errors that can occur when using scanf. Therefore, it is best to keep the description of scanf C before your eyes when programming. In large professional projects, iostreams are used due to the fact that they have higher-level capabilities, are better able to catch and process errors, and also work with significant amounts of information. It should also be noted that a 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.

C++ programming language

Last update: 08/28/2017

The C++ programming language is a high-level, statically typed, compiled, general-purpose programming language that is suitable for creating a wide variety of applications. Today, C++ is one of the most popular and widespread languages.

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 working 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 object-oriented programming capabilities. And that’s why Stroustrup himself initially called it “C with classes.”

Subsequently, the 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 from then on, 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 use in system programming, in particular, when creating operating systems, drivers, various utilities, antiviruses, etc. By the way, Windows OS is mostly written in C++. But the use of this language is not limited to system programming. C++ can be used in programs of any level where speed and performance are important. It is often used to create graphical applications and various application programs. It is also especially often used to create games with rich, rich visualization. In addition, recently the mobile direction has 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 supporting services that serve web applications. In general, C++ is a widely used language in which you can create almost any type of program.

C++ is a compiled language, which means that the compiler translates C++ source code 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 largely portable unless some OS-specific functions are used. And the availability of compilers, libraries and development tools for almost all common platforms allows you 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. Which simplifies the creation of large applications.

Main stages of development

In 1979-80, Bjarne Stroustrup developed an extension to the C language - "C with Classes". In 1983 the language was renamed 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.

In 1989, a new version of the C++ 2.0 language was released, which included a number of new features. After this, 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 organization (International Organization for Standardization). The first standard was called ISO/IEC 14882:1998, or C++98 for short. Subsequently, 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 with a large number of new functionality. Following this, a small addition to the standard, also known as C++14, was released in 2014. 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 the source code in C++ into an executable file, which you can then run. But at the moment there are many 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 are developing and implement all the latest standards. Thus, throughout this tutorial we will primarily use the freely available g++ compiler developed by the GNU project.

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

© 2023 hecc.ru - Computer technology news