C++输出

What is cout?

  1. std::ostream cout;

cout是一个变量,描述了一个对象,对象的类型是ostreamstd是所属的命名空间(防止重名)。
cout is an object of data type ostream in namespace std.

  1. cout << "hello." << endl;

<< 是运算符,它采用运算符重载来定义的,下图是其源码中的定义
<< is an operator which is defined as follows
image.png
定义其实就是一个函数operator <<,然后跟参数列表。第一行是对shot类型的输出的定义,返回类型为basic_ostream

理解了图中<< 的定义方式,那么cout << "hello." 就可以看作一次函数调用,函数的返回值依然是cout。

endl 就是endline,一行的结束,可以输出一个换行符
endl, an output-only I/O manipulator. It will output a new line character and flushes.

C++输入

  1. int a;
  2. float b;
  3. cin >> a;
  4. cin >> b;

Similarly, cin is an object of type std::istream.
输入和输出类似,cin的类型是命名空间std中的istream对象。

>> is an operator
>><<同理,也是运算符。

C风格输入输出

  1. // output
  2. int v = 100;
  3. printf("Hello, value = %d\n", v);

printf( const char *format, ... );is a function
printf函数中的第一个参数是一个字符串,字符串里头要注意需要指定数据类型
format: a string specifying how to interpret the data

%d will let the function interpret v as an integer
%d 用来指定后面参数v的数据类型,以整数类型将v打印出来。
% 的数量要和后面的参数数量要对应。

  1. // input
  2. int v;
  3. int ret = scanf("%d", &v); // & 取地址,然后将输入内容放到地址。
  4. // 从标准输入获取数据并将其转换成一个整数

scanf reads data from stdin, and interpret the input as an integer and store it into v;

Why not GUI

以上所有例子都是从标准输入输出,也就是从命令行中去输入输出,为什么不用GUI,应用程序不应该有图形界面吗。
The programs I used all have GUI. Why the examples have no GUI?

  • GUI (graphical user interface) is not mandatory. GUI 不是一个程序必须的功能和特性
  • GUI is for human beings to interact with computers. GUI为了人与计算机交互方便所提供的可视化界面。
  • No all programs interact with human beings.不是所有的程序都需要与人进行交互。
  • We can also interact with the program in a command line window.人也可以通过命令行与程序进行交互
  • We can call a GUI library to create a graphic window by many programming languages. Surely C/C++ can create a GUI window.

如果想创建GUI,只需调用特定的库就可以完成,不同的操作系统有不同的库,很难做到跨平台。

命令行参数 Command line arguments

如何通过命令行与程序进行交互:

  1. 通过命令行参数,把特定的命令发给程序,让程序按照你的指令去做。

Do you still remember?
g++ hello.cpp -o hello。g++也是一个应用程序,g++ is an executable program/file,There are three command line arguments
g++去编译hello.cpp 源文件,然后把结果存入到hello中,这就是通过命令行与程序进行交互,告诉程序编译hello.cpp,输出内容到hello中。

那么程序是怎么获取用户的输入呢?通过命令行参数,我们之前的main函数中是没有参数的,实际上,完整的main函数使有两个参数的,一个参数叫做argc(arguments cout 有多少参数),另一个参数叫做argv(具体的参数列表,会放到一个数组里面,数组里头的元素是一个字符串)

  1. int main()
  2. {
  3. /* ... */
  4. }
  5. int main(int argc, char *argv[])
  6. {
  7. ...
  8. }
  9. int main(int argc, char **argv)
  10. {
  11. ...
  12. }
  1. // argument.cpp
  2. #include <iostream>
  3. using namespace std;
  4. int main(int argc, char * argv[])
  5. {
  6. for (int i = 0; i < argc; i++) // 遍历所有的输入参数
  7. cout << i << ": " << argv[i] << endl;
  8. }

image.png

IDE

I don’t like to compile a program in a command window, you need a IDE

IDE: Integrated development environment

  • Microsoft Visual Studio
  • Apple Xcode
  • Eclipes
  • Clion

Visual Studio Code (VSCode) is an integrated development environment made by Microsoft for Windows, Linux and macOS