C++输出
What is cout?
std::ostream cout;
cout
是一个变量,描述了一个对象,对象的类型是ostream
,std
是所属的命名空间(防止重名)。
cout is an object of data type ostream in namespace std.
cout << "hello." << endl;
<<
是运算符,它采用运算符重载来定义的,下图是其源码中的定义<<
is an operator which is defined as follows
定义其实就是一个函数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++输入
int a;
float b;
cin >> a;
cin >> b;
Similarly, cin is an object of type std::istream.
输入和输出类似,cin
的类型是命名空间std
中的istream
对象。
>>
is an operator>>
和<<
同理,也是运算符。
C风格输入输出
// output
int v = 100;
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
打印出来。%
的数量要和后面的参数数量要对应。
// input
int v;
int ret = scanf("%d", &v); // & 取地址,然后将输入内容放到地址。
// 从标准输入获取数据并将其转换成一个整数
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
如何通过命令行与程序进行交互:
- 通过命令行参数,把特定的命令发给程序,让程序按照你的指令去做。
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
(具体的参数列表,会放到一个数组里面,数组里头的元素是一个字符串)
int main()
{
/* ... */
}
int main(int argc, char *argv[])
{
...
}
int main(int argc, char **argv)
{
...
}
// argument.cpp
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
for (int i = 0; i < argc; i++) // 遍历所有的输入参数
cout << i << ": " << argv[i] << endl;
}
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