- Bjarne Stroustrup 对C语言进行了扩展和创新,取名为 C With Class
- 到了1983年正式改名为C++,既支持面向过程的编程模式,又新增了 面向对象编程模式和泛型编程模式
HelloWorld
vim 01helloworld.cpp
cpp
#include <iostream>
using namespace std;
int main(void){
cout << "helloworld!" << endl;
return 0;
}
bash
g++ 01helloworld.cpp -o helloworld
#或者
gcc 01helloworld.cpp -o helloworld -lstdc++
./helloworld
cpp
/*
C++ 使用IO相关的函数时的标准头文件 类似于 stdio.h
C++风格的很多头文件没有.h后缀
C++兼容C, C++中可以使用stdio.h 也提供了C++风格的头文件 cstdio
该头文件一般位于 /usr/include/c++/编译器版本/
*/
#include <iostream>
/*名字空间*/
using namespace std;
int main(void){
/*类似于 printf("helloworld\n")
cout 输出对象
<<, 输出插入运算符
endl, 相当于 '\n'
*/
cout << "helloworld!" << endl;
return 0;
}
数据的输入输出
流的概念
- C++ 中的输入与输出可以看做是一连串的数据流,输入即可视为从文件或键盘中输入程序中的一串数据流,而输出则可以视为从程序中输出一 连串的数据流到显示屏或文件中
- 输入流: 从输入设备流向内存的字节序列
- 输出流: 从内存流向输出设备的字节序列
cout和插入运算符<<
- 当程序执行都cout语句时,遇到<<运算符就会将要是输出的信息插入到输出流中去,最终将输出流中的数据会被输出到标准输出设备(通常为屏幕)上去
cpp
cout<<x;
- 输出时自动判断基本数据类型的类型
c
#include <iostream>
using namespace std;
int main(void){
int x = 10;
float y = 1.1;
char z = 'c';
/*
*printf("%d %f %c\n", x, y,z);
* */
cout << x <<" "<< y <<" "<< z << endl;
return 0;
}
- cout的优势在于自动解析这些基本数据类型,cout也可以格式化输出
cin和析取运算符>>
- 当程序执行到cin语句时,就会停下来等待键盘数据的输入
- 输入数据被插入到输入流中,数据输完后按Enter键结束
- 当遇到运算符>>时,就从输入流中提取一个数据,存入变量x中
cpp
cin >>x;
- 在一条cin语句中可以同时为多个变量输入数据,各输入数据之间用一个或多个空白作为间隔符
cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main(void){
int x, y, z;
#if 0
scanf("%d %d %d", &x, &y, &z);
printf("%d %d %d\n", x, y, z);
#endif
cin >> x >> y >> z;
cout << x << " " << y << " " << z << endl;
return 0;
}
- cin具有自动识别数据类型的能力,析取运算符>>根据它后面的变量类型从输入流中为他们提取对应的数据
- 比如: cin >>x; 假设输入数据2, 析取运算符>>将根据其后x的类型决定输入的2到底是数字还是字符。若x是char类型,则2就是字符;若x是int,float之类的类型,则2就是一个数字。假设输入34,且x是char类型,则只有字符3被存储到x中,4将继续保存在流中
cpp
#include <iostream>
using namespace std;
int main(void){
int a;
double b;
char c;
cin >> a >> b >> c; //12.34a
cout << "a: " << a << " b: " << b << " c: " << c << endl; //a:12 b:.34 c:'a'
return 0;
}