# Essential C++ Reading Notes #Chapter 1 C++ Programming Foundation

Posted by jchemie on Fri, 24 Jan 2020 10:10:05 +0100

Preface

C++ Primer by Stanley B.Lippman is a very good textbook for learning C++, but C++ Primer, as a large first book, is obviously not suitable for all beginners.So Mr. Lippman returned to writing this short and light Essentia C++.This book helps beginners learn C++ grammar quickly, understand C++ language characteristics, and understand the design purpose and basic principles of C+.The author is reading the Chinese version of Essential C++, whose translator is named Hou Ji, and he is also a translator of the third Chinese version of C++ Primer.

Fundamentals

The first complete C++ program:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string user_name;
    cout << "Please enter your first name:";
    cin >> user_name;
    cout << '\n'
        << "Hello, "
        << user_name
        << "...and goodbye!\n";
    return 0;
}

Keyword is the pre-defined name of a program language that has special meaning.

A function is a separate sequence of program code that can perform some operations.It consists of four parts, return type, function name, parameter list, and function body.Main is not a keyword defined by the program language, but the C++ compilation system assumes that there is a main() function defined in the program.The main() function is the starting point for program execution, and if we do not define it, the program will not be able to execute.

The class mechanism gives us the ability to "increase the level of type abstraction within a program".The class mechanism allows us to incorporate data types into our programs and have the ability to recognize them.Object-oriented class hierarchy defines the related types of the entire family system.The definition of class is generally divided into two parts, written in separate files.One is the so-called header file, which declares the various operations provided by the class.Another file, program text, contains the implementation of these behaviors.To use a class, we must first include its header file in the program, which lets the program know the definition of the class.

Namespace is a way to encapsulate library names.In this way, naming conflicts with the application can be avoided (so-called naming conflicts refer to two different entities within the application having the same name), which makes it impossible for the application to distinguish between them.When a naming conflict occurs, the program must wait until the naming conflict is resolved before continuing.Namespaces are like walls built around visible enclosures of many names.

In order to define an object, we must name it and assign it a data type.Object names can be any combination of letters, numbers, underlines, and are case sensitive.Object names cannot begin with a number.Of course, any naming cannot exactly match the keywords of the program language itself.For example, delete is a language keyword, so string class es use earse() instead of delete() to indicate why a character is deleted.

The template class allows us to define a class without specifying the data member type.The template class mechanism allows programmers to decide the true data type until they use the template class.Programmers can insert a proxy name before binding to the actual data type.

Since the backslash character is used as the beginning character of the escape character, two consecutive backslashes represent a true backslash character.

An object defined as a const cannot be changed after it has an initial value.If you attempt to specify a new value for a const object, a compilation error will occur.

For the OR logical operator (||), the left expression is evaluated first, and if it is true, the remaining expression does not need to be evaluated (so-called short-circuit evaluation).The AND logical operator (&&), the leftmost expression is evaluated first. If the result is false, the AND operator is evaluated false, and the rest of the expressions are not evaluated.

Some operators have the same precedence as others. Operators in the same row have the same precedence, and their evaluation order depends on their position in the expression (from left to right).

Logical Operator NOT

Arithmetic operators (*, /,%)

Arithmetic Operators (+, -)

Relational Operators (<, >, <=, >=)

Relational Operator (==,!=)

Logical operator AND

Logical Operator OR

Assignment operator (assignment =)

To access an object that is pointed to by a pointer, we must take a dereference (also known as dereference) action on the pointer -- that is, get the object "at the memory address that the pointer points to".This can be achieved by using the'*'sign before the pointer.

We can use the dot member selection operator to select the operation we want.If you want to select an operation through a pointer, you must use the arrow member selection operator instead.If you want to use a subscript operator, you must first pull the pointer, because the subscript operator has a higher priority, so you must place parentheses around the pointer pull operation.

Exercise Answers

Exercise 1.5 Write a program that asks for the user's name and reads what the user has entered.Make sure the name entered by the user is longer than two characters.If the user does enter a valid name, respond with some information.There are two ways to do this: the first uses a C-style string and the second uses a string object.

#include <iostream>
#include <string>
#include <iomanip>
#include <cstring>

using namespace std;

#define MAX 50
#define MIN 2

int main()
{
    //C-style Character string
/*
    const int nm_size = 128;    //Assign a fixed size
    char user_name[nm_size];
    cout << "Please enter your name:";
    cin >> setw(nm_size) >> user_name;    //Ensure that no more than 127 characters are read in and null is saved in the last space
    size_t len = strlen(user_name);
    if (len <= 3)
    {
        cout << "Please enter a longer name!" << endl;
        return 0;
    }
    cout << "Hello," << user_name << endl;
*/

    //string object
    string user_name;
    cout << "Please enter your name:";
    cin >> user_name;
    size_t len = user_name.size();    //Get the string length, none null
    if (len <= 2)    
    {
        cout << "Please enter a longer name!" << endl;
        return 0;
    }
    cout << "Hello," << user_name << endl;
    return 0;
}

Exercise 1.6 Write a program that reads a series of integers from a standard input device, places the read integers in array s and vector s, and then traverses the containers to find the sum of the values.Output the sum and average values to the standard output device.

#include <iostream>
#include <vector>

using namespace std;

#define MAX 10

int main()
{
/*
    //Store in vector
    vector<double> v;
    double temp=0;
    double sum = 0;
    double ave = 0.0;
    while (cin >> temp)
    {
        v.push_back(temp);
    }
    for (int i = 0;i < v.size();i++)
    {
        sum += v[i];
    }
    ave = sum / v.size();
    cout << "Sum=" << sum << endl;
    cout << "Average=" << ave << endl;
*/
    //Store in array
    double arr[MAX];
    int count = 0;
    int count2 = 0;
    double temp;
    double sum = 0.0;
    double ave = 0.0;
    while (count<10 && cin >> temp)
    {
        arr[count] = temp;
        count++;
    }
    count2 = count;
    count--;
    while (count >= 0)
    {
        sum += arr[count];
        count--;
    }
    ave = sum / count2;
    cout << "Sum=" << sum << endl;
    cout << "Average=" << ave << endl;
    return 0;
}

Exercise 1.7 Enter two (or more) lines of text on a disk using your best-known editing tool.Then write a program that opens the text file and reads each word into a vector<string>object.Traverse the vector to display the contents to the cout.Then all words are sorted using the generic algorithm sort().

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

int main()
{
    ifstream in_file("1.txt");
    if (!in_file)
    {
        cerr << "opps! unable to open input file\n";
        return -1;
    }
    ofstream out_file("2.txt");
    if (!out_file)
    {
        cerr << "opps! unable to open output file\n";
        return -1;
    }
    string word;
    vector<string> text;
    while (in_file >> word)
        text.push_back(word);
    size_t ix;
    cout << "unsorted text:\n";
    for (ix = 0;ix < text.size();++ix)
    {
        cout << text[ix] << ' ';
    }
    cout << endl;
    sort(text.begin(), text.end());
    cout << "sorted text:\n";
    for (ix = 0;ix < text.size();++ix)
    {
        cout << text[ix] << ' ';
        out_file << text[ix] << ' ';
    }
    cout << endl;
    out_file << endl;
    return 0;
}

Exercising the switch statements in section 1.8 1.4 allows us to provide different comfort statements depending on how many times the user has answered incorrectly.Show the comfort statement by storing four different string information in array and using the number of user errors as the index value for array.

#include <iostream>
#include <stdlib.h>
#include <ctime>

using namespace std;

const char* msg_to_usr(int num_tries);

int main()
{
    int count=0;
    srand(time(0));
    int answer = rand() % 3;
    int myAnswer;
    char isContinue = 'y';
    while (isContinue=='y')
    {
        cout << "Please input your answer(0-2): ";
        cin >> myAnswer;
        if (myAnswer == answer)
        {
            cout << "Congratulations!" << endl;
            break;
        }
        else
        {
            count++;
            cout << msg_to_usr(count) << endl;
            cout << "Continue? input y or n: ";
            cin >> isContinue;
        }
    }
    return 0;
}

const char* msg_to_usr(int num_tries)
{
    const int rsp_cnt = 5;
    static const char* usr_msgs[rsp_cnt] =
    {
        "Go on, make a guess. ",
        "Oops! Nice guess but not quite it. ",
        "Hmm. Sorry. Wrong a second time. ",
        "Ah, this is harder than it looks, no? ",
        "It must be getting pretty frustrating by now! "
    };
    if (num_tries < 0)
    {
        num_tries = 0;
    }
    else if (num_tries >= rsp_cnt)
        num_tries = rsp_cnt - 1;
    return usr_msgs[num_tries];
}

end.

"If you take it from above, you get it from there; if you take it from below, you get nothing."

Topics: C++ REST