欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++学习系列二:Operators||Basic Input/Output

程序员文章站 2022-06-01 11:13:41
...
  • Operators

    1. Assignment operator(=)

      The assignment operator assigns a value to a variable.

      Assignment operations are expressions that can be evaluated. That means that the assignment itself has a value, and - for fundamental types - this value is the one assigned in the operation.

      y = x + (x = 5);
      x = y = z = 5;
      
    2. Arithmetic Operators (+, -, *, /, %)
      Operator Description
      + addition
      - subtraction
      * multiplication
      / division
      % modulo 模除(取余), gives the remainder(余数) of a division of two values
    3. Compound Assignment(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) 复合赋值

      Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand(运算对象):

      expression equivalent to …
      y += x; y = y + x;
      x -= 5; x = x -5;
      x /= y; x = x / y;
      price *= units + 1; price = price * (units + 1);
    4. Increment and decrement (++, --)

      The increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively.

      A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable name(++x) or after it (x++).

      • In simple expressions like x++ or ++x, both have exactly the same meaning

      • In other expressions in which the result of the increment or decrement operation is evaluated, they may have an important difference in their meaning:

        1. In the case that the increase operator is used as a prefix(++x) of the value, the expression evaluates to the final value of x, once it is already increased

        2. On the other hand, in case that it is used as a suffix (x++), the value is also increased, but the expression evaluates to the value that x had before being increased

          Example 1 Example 2
          x = 3;
          y = ++x;
          // x contains 4, y contains 4
          x = 3;
          y = x++;
          //x contains 4, y contains 3
    5. Relational and Comparison Operators (==, !=, >, <, >=, <=)

      The result of such an operations is either true or false.

      Operator Description
      == Equal to
      != Not equal to
      < Less than
      > Greater than
      <= Less than or equal to
      >= Greater than or equal to

      Of course, it’s not just numeric constants that can be compared, but just any value, including, of course, variables.

    6. Logical Operators (!, &&, ||)

      The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand , to its right, and inverts it.

      !true // evaluates to false

      && and

      || or

      The logical operators && and || are used when evaluating two expressions to obtain a single relational result.

    7. Conditional ternary operator (?)

      The conditional operator evaluates an expression, returning one value if that exprssion evaluates to true, and a different one if the expression evaluates as false. Its syntax is :

      condition ? result1 : result2

      If condition is true, the entire expression evaluates to result1, and otherwise to result2.

    8. Comma operator (,)

      The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

      For example, the following code:

      a = (b=3, b+2);

      would first assign the value 3 to b, and then assign b+2 to variable a. At the end, variable a would contain the value 5 while variable b would contain value 3.

    9. Bitwise Operators (&, |, ^, ~, <<, >>)

      Bitwise operators modify variables considering the bit patterns that represent the values they store.

      Operator Asm Equivalent Description
      & AND Bitwise AND
      | OR Bitwise inclusive OR (位或)
      ^ XOR Bitwise exclusive OR
      ~ NOT Unary complement (bit inversion)
      << SHL Shift bits left
      >> SHR Shift bits right
    10. Explicit type casting operator 显示类型转换操作符

      Type casting operators allow to convert a value of a given type to another type.

      There are several ways to do this in C++.

      • The simplest one (which has been inherited from the C language) is to precede the expression to be converted by the new type enclosed between parentheses(())

        int i;
        float f = 3.14;
        i = (int) f;
        
      • Another way to do the same thing in C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:

        i = int (f);
        
    11. sizeof

      This operator accepts one parameter, which can be either a type or a vaiable, and returns the size in bytes of that type or object:

      x = sizeof(char);
      

      Here, x is assigned the value 1, because char is a type with a size of one byte.

      The value returned by sizeof is a compile-time constant, so it is always determined before program execution.

    12. Other Operators
    13. Precedence of Operators

      From greatest to smallest priority, C++ operators are evaluated in the following order:

      C++学习系列二:Operators||Basic Input/Output

      When an expression has two operators with the same precedence level, grouping determines which one is evaluated first: either left-to-right or right-to-left .

  • Basic Input / Output

    C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen, the keyboard or a file.

    A stream is an entity where a program can either insert or extract characters to/from.

    All we need to know about the media associated to the stream is that strams are a source/destination of characters, and that these characters are provided/accepted seqentially (i.e., one after another).

    The standard library defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:

    Stream Description
    cin standard input stream
    cout standard output stream
    cerr standard error (output) stream
    clog standard logging (output) stream

    We are going to see in more detail only cout and cin (the standard output and input streams); cerr and clog are also output streams, so they essentially work like cout, with the only difference being that they identify streams for specific purposes: error messages and logging.

    1. Standard Output (cout)

      On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.

      For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two “less than” signs)

      cout << "Output sentence"; 
      cout << 120;
      cout << x;
      // Multiple insertion operations may be chained in a single statement
      cout << "This " << "is a " << "Single C++ statement"; // print the text This is a single C++ statement
      

      The << operator inserts the data that follows it into the stream that precedes it.

      Chaining insertions is especially useful to mix literals and variables in a single statement.

      What cout does not do automatically is add line breaks at the end, unless instructed to do so.

      In C++, a new-line character can be specified as \n. Alternatively, the endl manipulator can also be used to break lines. What’s the differences between them is the endl also has an additional behavior: the stream’s buffer is flushed.

      cout << 'First sentence.\n';
      cout << "First sentence." << endl;
      
    2. Standard Input (cin)

      In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.

      For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two greater than signs). The operator is then followed by the variable where the extracted data is stored.

      int age;
      cin >> age;
      

      The first statement declares a variable of type int called age, and the second extracts from cin a value to be stored in it.

      This operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the keyboard.

      Extractions on cin can also be chained to request more than one datum in a single statement:

      cin >> a >> b;

    3. cin and strings

      The extraction operator can be used on cin to get strings of characters in the same way as with fundamental data types:

      string mystring;
      cin >> mystring;
      

      However, cin extraction always considers spaces (whitespaces, tabs, new-line, ...) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.

      To get an entire line from cin, there exists a function, called getline, that takes the stream (cin) as first argument, and the string variable as second.

      Unless you have a strong reason not to, you should always use getline to get input in your console programs instead of extracting from cin.

    4. Stringstream

      The standard header defines a type called stringstream that allows a string to be treated as a stream, and thus allowing extraction or insertion operations from/to strings in the same way as they are performed on cin and cout.

      This feature is most useful to convert strings to numerical values and vice versa.