C++快速入门1

116 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

C标准库、注释、条件编译

C++包含了C标准库的移植版本,C标准库的头文件由x.h变为了cx,如:stdio.h变为了cstdio,math.h变为了cmath,string.h变为了cstring。(原本的也还能用,如stdio.h、math.h、string.h等)

但不是所有的都移植了,例如用于动态内存分配的:malloc.h

注释

多行注释/* */

单行注释 //

预处理指令

#开头的为预处理指令,由预处理器进行处理,处理完后再交给编译器编译

如果不满足条件,就会把那块代码舍弃掉

//一个条件时
#if 0
	...
#endif

//两个条件时
#if 1
	...
#else
	...
#endif

//多个条件时
#if 1
    ...
#elif
    ...
#elif
    ...
#endif

//如果定义了某个宏就编译
#ifdef xx
    ...
#endif

//如果没定义某个宏
#ifndef xx
    ...
#else
    ...
#e

例子:

#if 0
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
    ofstream oF("a.txt");
    oF << 3.14 << "hello world" << endl;
    oF.close();
    ifstream iF("a.txt");
    double a;
    string s;
    iF >> a >> s;
    cout << a << s << endl;
    return 0;
}
#endif
#include<iostream>
using namespace std;
int main(){
    cout << "hello world" << endl;
    return 0;
}

在这一段中仅编译了endif后面那一段

image.png

标准输入输出流和名字空间

iostream:标准输入输出流文件

C++把输入输出看作字节流向外部设备输出或者从外部设备输入

cout是一个标准输入输出流对象,代表控制台窗口

<<是输出流运算符,假如o是一个输出流对象,x是数据,o << x的返回结果仍然是一个输出流对象

cout是标准名字空间std的一个名字,要使用必须加上名字空间限定std::std::cout,也可以在开头加上using std::cout之后使用就不用写std了,还可以using namespace std引入整个名字空间

>>是输入流运算符,cin是标准输入流对象

fstream:文件输入输出流

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
    ofstream oF("a.txt");
    oF << 3.14 << "hello world" << endl;
    oF.close();
    ifstream iF("a.txt");
    double a;
    string s;
    iF >> a >> s;
    cout << a << s << endl;
    return 0;
}
3.14hello