C++学习系列二:Operators||Basic Input/Output
-
Operators
-
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;
-
Arithmetic Operators (
+, -, *, /, %
)Operator Description + addition - subtraction * multiplication / division % modulo 模除(取余), gives the remainder(余数) of a division of two values -
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); -
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:
-
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
-
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 4x = 3;
y = x++;
//x contains 4, y contains 3
-
-
-
Relational and Comparison Operators (
==, !=, >, <, >=, <=
)The result of such an operations is either
true
orfalse
.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.
-
Logical Operators (
!, &&, ||
)The operator
!
is the C++ operator for the Boolean operationNOT
. 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. -
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 asfalse
. Its syntax is :condition ? result1 : result2
If
condition
istrue
, the entire expression evaluates toresult1
, and otherwise toresult2
. -
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
tob
, and then assignb+2
to variablea
. At the end, variablea
would contain the value5
while variableb
would contain value3
. -
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 -
Explicit type casting operator 显示类型转换操作符
Type casting operators allow to convert a
value
of a giventype
to anothertype
.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);
-
-
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 value1
, 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.
-
Other Operators
-
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:
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
andcin
(the standard output and input streams);cerr
andclog
are also output streams, so they essentially work likecout
, with the only difference being that they identify streams for specific purposes: error messages and logging.-
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, theendl
manipulator can also be used to break lines. What’s the differences between them is theendl
also has an additional behavior: the stream’s buffer is flushed.cout << 'First sentence.\n'; cout << "First sentence." << endl;
-
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 theextraction 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
calledage
, and the second extracts fromcin
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;
-
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 fromcin
. -
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 oncin
andcout
.This feature is most useful to convert strings to numerical values and vice versa.
-