一.常用命令
1.C++程序的基本框架:
#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl;//输出hello world到屏幕
system("pause");
return 0;
}
//结果:
hello world
2.关键字
asm | auto | bool | break | case | catch |
---|---|---|---|---|---|
char | class | const | const_cast | continue | default |
delete | do | double | dynamic_cast | else | enum |
explicit | export | extern | false | float | for |
friend | goto | if | inline | int | long |
mutable | namespace | new | operator | private | protected |
public | register | reinterpret_cast | return | short | signed |
sizeof | static | static_cast | struct | switch | template |
this | throw | true | try | typedef | typeid |
union | unsigned | using | virtual | void | volatile |
wchar_t | while |
3.IO
(1)输出到屏幕:
cout << <var1>[ << <var2> << endl];
//endl用于输出换行符并刷新输出流
//参数说明:
var:指定要输出的内容
//如果有多个,越靠左的越先输出
//实例:
#include <iostream>
using namespace std;
#include <string>
int main() {
int i = 12;
string s = "hello";
char c = 's';
cout << i << s << "hhh" << c << 666 << endl;
system("pause");
return 0;
}
//结果:
12hellohhhs666
(2)从键盘输入:
cin >> <var>;
//回车表示输入完毕;注意不要输入类型与<var>不同的数据
//参数说明:
var:指定输出到的变量
//实例:
#include <iostream>
using namespace std;
#include <string>
int main() {
string s;
float f;
double d;
char c;
bool b;
cout << "请输入string s的值:";
cin >> s;
cout << "请输入float f的值:";
cin >> f;
cout << "请输入double d的值:";
cin >> d;
cout << "请输入char c的值:";
cin >> c;
cout << "请输入bool b的值:";
cin >> b;
cout << s << f << d << c << b << endl;
system("pause");
return 0;
}
//结果:
请输入string s的值:sasa
请输入float f的值:32.1
请输入double d的值:32.1
请输入char c的值:e
请输入bool b的值:222//不能直接输入true/false//任何非0值都被当作true
sasa32.132.1e1
二.数据类型
注意:
①以下只说明C++对C的扩展,与C相同的数据类型请参见C
②C++中对数据类型转换的要求比C要严格得多
1.字符串型
(1)C风格:
同C语言的字符数组(参见 C语言基础.数组.六 部分)
(2)C++风格:
string <sname>="<str>";
//注意:需要包含string头文件(不过由于头文件依赖,不包含也有可能可以)
//参数说明:
sname:指定变量名
str:指定变量值
//实例:
#include <iostream>
using namespace std;
#include <string.h>
//#include <string>//也可以不加后缀名.h
int main() {
string str = "hello world";
cout << str << endl;
system("pause");
return 0;
}
2.宽字符型:
宽字符型(wchar_t)实际上就是short int:
typedef short int wchar_t