C++primer First Chapter Quick Start

Source: Internet
Author: User

This chapter describes most of the basic features of C + +: Built-in types, library types, class types, variables, expressions, statements, and functions.

In this process, you will also briefly describe how to compile and run the program.

To learn a new programming language, you must actually write the program. In this chapter, we will solve a simple data processing problem with the abbreviation program: A bookstore saves each transaction in a file format. Each transaction records the sales of a book, containing the ISBN (ISBN, the unique identifier of each book in the world), the number of sales volumes, and the sales unit price. Each deal is shaped like:
0-201-70353-x 4 24.99

Before you write this program, you must know some of the basic features of C + +. At least we need to know how to write, compile, and execute simple programs. What does this program do? Although no solution has been designed yet, we know that the program must:

    • Defines a variable.
    • Implement input and output.
    • Define the data structure to hold the information to be processed.
    • Tests whether two records have the same ISBN.
    • Write loops. Process each record in the transaction file.

1.1. Writing a simple C + + program

Each C + + program contains one or more functions, and must have a name of main. A function consists of a sequence of statements that perform function functions. The operating system executes the program by calling the main function, and the main function executes the statement that makes up its own and returns a value to the operating system.

  

int Main () {    return0;}

Defining the main function is the same as defining other functions. The definition function must specify 4 elements: The return type, the function name, the formal parameter list within the parentheses (possibly empty), and the body of the function.

The return value of the main function must be of type int, which represents an integer. The int type is a built-in type, meaning that the type is defined by the C + + language.

The last part of a function body function definition is a block of statements that begins with curly braces and ends in curly braces:
{
return 0;
}

In most systems, the return value of the main function is a status indicator. A return value of 0 often indicates that the main function completed successfully. Any other nonzero return value has the meaning of the operating system definition. Typically a non-0 return value indicates that an error occurred. Each operating system has its own way of telling the user what the main function is returning.

1.1.1. Compiling and executing programs

Many PC-based compilers run in the integrated development environment (IDE), and the IDE binds the compiler to related build and analysis tools.

  Program source file naming specification

  Whether we use the command line interface or the IDE, most compilers expect the program to be compiled to be saved in the
File. Program files are called source files.

The system we use to compile the instance of this book treats the file with the suffix. cc as a C + + program, so we save the program as:
prog1.cc

1.2. First Glimpse input/output

Most of the examples in this book use the iostream library that handles formatted input and output. The base of the iostream library is the two types named IStream and Ostream, which represent the input and output streams, respectively. A stream is a sequence of characters to be read or written out of an IO device. The term "stream" attempts to illustrate that characters are generated or consumed in chronological order.

1.2.1. Standard input and Output objects

The standard library defines 4 IO objects. The input is processed using an IStream type object named CIN (read as see-in). This object is also known as standard input. The output is processed using an Ostream type object named cout (read as See-out), which is also known as standard output. The standard library also defines two additional Ostream objects, named Cerr and clog (read as "See-err" and "See-log", respectively). The Cerr object is also known as a standard error, and is often used to output warnings and error messages to the user of the program. The clog object is used to generate general information about program execution.

1.2.2. A program that uses the IO library

So far, we have learned how to compile and execute simple programs, although that program does nothing. In the beginning of the bookstore problem, some records contain the same ISBN, you need to summarize these records, that is, you need to figure out how to accumulate the number of books sold.

1#include <iostream>2 intMain ()3 {4Std::cout <<"Enter The numbers:"<<Std::endl;5     intv1, v2;6Std::cin >> v1 >>v2;7Std::cout <<"The sum of"<< v1 <<" and"<<v28<<" is"<< V1 + v2 <<Std::endl;9     return 0;Ten}

The first line of the program is a preprocessing instruction:
#include <iostream>
Tells the compiler to use the iostream library. The name in the angle brackets is one. Header file. The program must include the associated header file when using the Library tool.

Write to stream

The first statement in the main function body executes an expression. In C + +, an expression consists of one or several operands and usually an operator. The expression of the statement uses the output operator (<< operator) to output the prompt on the standard output:
Std::cout << "Enter numbers:" << Std::endl;

  This statement uses the output operator two times. Each output operator instance accepts two operands: the left operand must be a Ostream object, and the right operand is the value to be output.

  Endl is a special value, called a manipulator, that has the effect of outputting a line break when it is written to the output stream, and refreshes the buffer associated with the device. By flushing the buffer, the user can immediately see the output written to the stream.

Use a name from the standard library

This program uses Std::cout and Std::endl instead of cout and Endl. Prefix std:: Indicates that cout and Endl are defined in the namespace Std. Using namespaces programmers can avoid unintentional collisions with names that are defined in the library.

The std::cout notation uses the scope operator (scope operator,:: operator), which indicates that the cout defined in the namespace STD is used.

Read the Inflow

After the prompt is output, the data entered by the user is read into. First define two variables named V1 and v2 to save the input:
int v1, v2;
These variables are defined as int types, which are built-in types that represent integer values.

The next statement reads the input:
Std::cin >> v1 >> v2;
The input operator (>> operator) behaves like an output operator. It takes a IStream object as its left operand, takes an object as its right operand, reads the data from the IStream operand, and saves it to the right operand. Like the output operator, the input operator returns its left operand as the result.

Complete the program

The rest is to output the result:
Std::cout << "The sum of" << v1 << "and" << v2<< "is" << v1 + v2 << std::en dl
Although this statement is longer than the output prompt, there is no conceptual difference. It outputs each operand to the standard output. Interestingly, operands are not all values of the same type, and some operands are string literals.

1.3. About annotations

  Before the program becomes more complex, we should understand how C + + handles annotations. Annotations can help others to read programs, often to summarize algorithms, confirm the purpose of variables, or clarify code snippets that are difficult to understand. Comments do not increase the size of the executable program, and the compiler ignores all comments.

There are two types of comments in C + +, single-line and paired-comments. The single-line comment begins with a double slash (//), and the content on the right side of the line is commented and ignored by the compiler.

Another delimiter, the comment pair (/*/), is inherited from the C language. This comment begins with "/*" and ends with "*/". The compiler notes the contents of "/**/" into comments:

1#include <iostream>2 /*Simple main function:read numbers and write their sum*/3 intMain ()4 {5     //Prompt user to enter numbers6Std::cout <<"Enter The numbers:"<<Std::endl;7     intV1, v2;//uninitialized8Std::cin >> v1 >> v2;//Read Input9     return 0;Ten}

Comment Pairs not nested

  Comments always start with/* and end with */. This means that one comment pair cannot appear in another annotation pair.

1#include <iostream>2 /*3 * Comment Pairs /**/cannot nest.4*"Cannot nest"  isconsidered source code,5* as  isThe rest of the program6*/7 intMain ()8 {9     return 0;Ten}

1.4. Control structure statements are always executed sequentially: The first statement of the function executes first, followed by the second, and so on. Of course, a handful of programs--including the procedure we will write to solve the bookstore problem--can be written in only sequential execution. In fact, the programming language provides a variety of control structures to support more complex execution paths. This section provides a brief introduction to the control structure provided by C + +, and the sixth chapter describes the various statements in detail.

1.4.1. While statement

1#include <iostream>2 intMain ()3 {4     intsum =0, val =1;5     //keep executing the while until Val was greater than6      while(Val <=Ten) {7Sum + = val;//assigns sum + val to sum8++val;//add 1 to Val9     }TenStd::cout <<"Sum of 1 to ten inclusive is" One<< sum << Std::endl;
return 0;
}

The while structure has this form:
while (condition) while_body_statement;

The while is repeated by testing condition (conditions) and performing related while_body_statement until condition is false.
A condition is an evaluated expression, so you can test its results. If the result value is nonzero, the condition is true, and if the value is zero, the condition is false.
If condition is true (the expression evaluates to not 0), the while_body_statement is executed. Once you're done, test condition again. If condition is still true, While_body_statement is executed again. The while statement continuously tests condition and executes while_body_statement until the condition is false.

The condition of the while statement uses the less than or equal to operator (<= operator), which compares the current value of Val to 10 and executes the while loop body as long as Val is less than or equal to 10.

A block is a sequence of statements enclosed in curly braces. In C + +, blocks can be used wherever a statement is available. The first statement in the block uses the compound assignment operator (+ = operator), which adds its right operand to the left operand, which is equivalent to writing a statement with an addition and an assignment:

sum = sum + val; Assign Sum + val to sum

Using the pre-increment operator (+ + operator), the increment operator is the same as adding 1,++val to its operand and val = val + 1.

1.4.2. For statement

#include <iostream>intMain () {intsum =0; //sum values from 1 up to ten inclusive     for(intval =1; Val <=Ten; ++val) sum+ = Val;//equivalent to sum = Sum + valStd::cout <<"Sum of 1 to ten inclusive is"<< sum <<Std::endl; return 0;}

Contains a For statement header and a for statement body two parts. The For statement header controls the number of executions of the for statement body.

The For statement header consists of three parts: an initialization statement, a condition, and an expression .

To recap, the total execution flow for the For loop is:

    1. Create Val and initialize to 1.
    2. Tests if Val is less than or equal to 10.
    3. If Val is less than or equal to 10, the for loop body is executed and Val is added to sum. If Val is greater than 10, it exits the loop and executes the first statement after the for statement body.
    4. Val increments.
    5. Repeat the 2nd step of the test and continue with the remaining steps as long as the condition is true.

1.4.3. If statement

The and of the number between 1 and 10, and its logical extension is the number of the two numbers provided by the user. You can use these two numbers directly in a for loop, using the first input value as the lower bound and the second input value as the upper bound. However, if the user is given a large number first, this strategy will fail: The program exits the for loop immediately. Therefore, we should adjust the range so that the larger number is the upper bound and the smaller number is the lower bound. In doing so, we need a way to determine which number is larger.

  

#include <iostream>intMain () {std::cout<<"Enter The numbers:"<<Std::endl; intv1, v2; Std::cin>> v1 >> v2;//Read Input//Use smaller number as lower bound for summation//and larger number as upper bound    intLower, Upper; if(V1 <=v2) {Lower=v1; Upper=v2; } Else{Lower=v2; Upper=v1; }    intsum =0; //sum values fromlower to and including Upper     for(intval = lower; Val <= Upper; ++val) sum+ = Val;//sum = sum + valStd::cout <<"Sum of"<<Lower<<" to"<<Upper<<"inclusive is"<< sum <<Std::endl; return 0;} 

1.4.4. Read in Unknown purpose input

 #include <iostream>int   main () {  int  sum = 0  , value;  //  read till end-of-file, calculating a Running total of allvalues read   value) Sum  + = value; //  equivalent to sum = sum + value  std::cout <<  " sum is:  "  << Sum <<< Span style= "color: #000000;"    > Std::endl;  return  0  ;}  

When we use the IStream object as a condition, the result is the state of the test flow. If the stream is valid (that is, if it is possible to read into the next input) then the test succeeds. When a file terminator is encountered or an invalid input is encountered, such as reading a value that is not an integer, the IStream object is invalid. A IStream object in an invalid state causes the condition to fail.

1.5. Introduction to Classes

  Before solving the bookstore problem, you need to figure out how to write a data structure to represent the transactions. In C + + We define our own data structures by defining classes. The class mechanism is one of the most important features in C + +. In fact, the main focus of C + + design is to make the behavior of the defined class type as natural as the built-in type. The library types we've seen earlier, like IStream and ostream, are defined as classes, that is, they are strictly not part of the language.

We need to answer three questions when using the class:

1. What is the name of the class?
2. Where is it defined?
3. What action does IT support?

1.5.1. Sales_item class

By convention, a class type is stored in a file whose file name is the same as the source file name of the program, and consists of a file name and a two-part suffix. Usually the file name and the class name defined in the header file are the same. The usual suffix is. h, but there are some programmers to use. H,. hpp or. hXX.

Actions on the Sales_item object

As with built-in types, you can define variables of class type. When you write down
Sales_item item;

In addition to defining variables of type Sales_item, we can also perform the following operations on the Sales_item object:
• Add two Sales_item using the addition operator, +.
• Use the input operator, <<, to read a Sales_item object.
• Use the output operator, >>, to output a Sales_item object.

• Assign a Sales_item object to another Sales_item object using the assignment operator =.
• Call the SAME_ISBN function to determine whether two sales_item refer to the same book.

1.6. C + + Programs

C++primer First Chapter Quick Start

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.