每个C++程序都包含一到多个函数,但必须有一个函数叫main
,如下:
int main(){
return 0;
}
每个函数都包含四个部分:
C++语言本身没有定义输入输出语句,需要包含额外的用于输入输出的标准库
。
iostream
是C++的一个标准库。
该文件定义了 cin、cout、cerr 和 clog 对象,
分别对应于标准输入流、标准输出流、非缓冲标准错误流和缓冲标准错误流。
举例:
#include <iostream>
int main(){
char str[200];
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
#include <iostream>
int main(){
std::cout << "Example for cout." << std::endl;
return 0;
}
#include <iostream>
int main(){
std::cerr << "Example for cerr." << std::endl;
return 0;
}
#include <iostream>
int main(){
std::clog << "Example for clog." << std::endl;
return 0;
}
cout语句的一般格式为: cout « 项目1 « 项目2 « … « 项目n;
功能:
在执行cout语句,先把数据放在输出缓冲区中,直到输出缓冲区满或遇到cout语句中的endl或’\n’为止, 此时将缓冲区中已有的数据一起输出,并清空缓冲区。输出遇到endl或’\n’换行。
为了区分相同的名字使用namespace
,在不同的namespace
中可以使用相同的名字。
可以用using namespace std
声明后续代码使用std
命名空间,如代码
#include <iostream>
int main(){
std::cout << "Example for cout." << std::endl;
return 0;
}
中的std
可以通过using namespace std
省略掉。
#include <iostream>
using namespace std;
int main(){
cout << "Example for cout." << endl;
return 0;
}
#include <iostream>
using namespace std;
int main(){
char s[200];
cin >> s;
cout << s << endl;
return 0;
}
cin 和 cout 是外部世界和程序通讯的指令
变量使用来保存数据的地方,如int a,b,c
中,a,b,c是变量,变量(筐)大小由前面int规定,由此a,b,c就是int那么大2^32,是个十位数。