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

本文详细介绍了C++中各种运算符的功能与用法,包括赋值、算术、复合赋值、递增与递减、关系与比较、逻辑、条件、逗号、位运算和类型转换等运算符。同时,还讲解了输入输出流的概念和基本使用方法。
  • 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 (+, -, *, /, %)
      OperatorDescription
      +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(运算对象):

      expressionequivalent 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 1Example 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.

      OperatorDescription
      ==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.

      OperatorAsm EquivalentDescription
      &ANDBitwise AND
      |ORBitwise inclusive OR (位或)
      ^XORBitwise exclusive OR
      ~NOTUnary complement (bit inversion)
      <<SHLShift bits left
      >>SHRShift 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:

      在这里插入图片描述

      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:

    StreamDescription
    cinstandard input stream
    coutstandard output stream
    cerrstandard error (output) stream
    clogstandard 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.

扩展名为 `.mts` 的文件通常与 TypeScript 模块相关,具体来说是用于 ECMAScript 模块(ESM)的 TypeScript 文件。以下是对 `.mts` 文件及其语法特点、特性的详细说明: ### 关于 `.mts` 文件 `.mts` 文件是 TypeScript 的一种模块文件格式,专为 ECMAScript 模块设计。它表示该文件是一个 ESM 模块,而不是传统的 CommonJS 模块[^1]。TypeScript 支持多种模块系统,包括 CommonJS、AMD、System、UMD 和 ES Module。当使用 `.mts` 扩展名时,TypeScript 编译器会自动将其视为 ESM 模块。 ### 语法结构 TypeScript 的 `.mts` 文件遵循标准的 ECMAScript 模块语法,同时结合 TypeScript 的类型系统特性。以下是其主要语法结构和特点: #### 1. 导入与导出 - 使用 `import` 和 `export` 语句来定义模块之间的依赖关系。 - 示例代码: ```typescript // 导入模块 import { add } from './math.mts'; // 导出函数或变量 export function subtract(a: number, b: number): number { return a - b; } ``` #### 2. 类型声明 TypeScript 提供强大的类型系统,支持接口、类、枚举等高级特性。 - 示例代码: ```typescript interface User { id: number; name: string; } export class UserManager { users: User[] = []; addUser(user: User): void { this.users.push(user); } } ``` #### 3. 装饰器与元编程 TypeScript 支持装饰器语法,可用于修改类或类成员的行为。 - 示例代码: ```typescript function log(target: any, key: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { console.log(`Calling ${key} with`, args); return originalMethod.apply(this, args); }; } class MathOperations { @log add(a: number, b: number): number { return a + b; } } ``` ### 特性 1. **模块化**:`.mts` 文件天然支持模块化开发,便于代码复用和维护。 2. **类型安全**:通过 TypeScript 的类型系统,可以在编译阶段捕获潜在的错误。 3. **现代 JavaScript 特性**:支持最新的 ECMAScript 特性,如 async/await、解构赋值等[^2]。 4. **工具链支持**:TypeScript 提供了丰富的工具链支持,包括编译器、语言服务和插件生态。 ### 注意事项 - 确保在 `tsconfig.json` 中正确配置模块类型为 `"module": "ESNext"` 或 `"module": "ES2022"`。 - 需要 Node.js 版本支持 ESM 模块(Node.js 12+)。 ```json { "compilerOptions": { "module": "ESNext", "target": "ES2022", "moduleResolution": "Node" } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值