文章目录
一个简单的C++程序
#include <iostream>
// 使用名为std的命名空间
using namespace std;
int main()
{
// printf ("hello world\n");
// cout 标准输出 往屏幕打印内容 相当于C语言的 printf
// << 左移操作符,在这里它的功能被改造,代表数据流向
// << 代表数据从右端移到左端 右端是 "hello world"字符串,左端是 cout 标准输出
// 所以 cout << "hello world" 代表将内容打印到标准输出
// endl 代表换行,相当于 C语言的 '\n'
// << 操作符可以连着使用
cout << "Hello World!" << endl;
return 0;
}
使用规范
将 std 直接声明在所有函数外部,这样虽然使用方便,但在中大型项目开发中是不被推荐的,这样做增加了命名冲突的风险,我推荐在函数内部声明 std。
例子:
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World"<<endl;
cout<<"hello \t World\n"; //C语言中的格式转换在C++中仍然适用
int age = 20;
char *name = "小小";
cout<<"age = "<<age<<",name = "<<name<<endl; //cout可以自动读取数据类型
printf("age = %d , name = %s\n",age,name);
int a;
float b;
cin>>a>>b;
cout<<"a = "<<a<<",b = "<<b<<endl;
printf("a = %d,b = %f\n",a,b);
return 0;
}
执行结果:
Hello World
hello World
age = 20,name = 小小
age = 20 , name = 小小
10 10.1
a = 10,b = 10.1
a = 10,b = 10.100000
请按任意键继续. . .