2.1 myfirst.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "Come up c++ some time.";
cout << endl;
cout << "You won't regret it!" << endl;
return 0;
}
刚开始预处理命令,将iostream文件的内容添加到程序中,io指的是输入输出,下面用到的cin/cout都包含在其中。另外c++不像c语言中头文件需要加.h,例如math.h。 main函数无需多说。 using namespace std; 名称空间,为避免与其他库名称重复,所以声明选用std中的名称(常量,变量,函数等) << 和 >>可理解为数据流向的方向,这在下面cin与cout的演示中将更加直观。 cout <<"",将后续""中的字符串插入到输出流中输出。 cout << endl; 重起一行,使光标到下一行c++,之后同理,可减少输入量,c++也可用"\n"换行。
2.2 carrots.cpp
#include <iostream>
int main()
{
using namespace std;
int carrots;
carrots = 25;
cout << "I have";
cout << carrots;
cout << "carrots.";
cout << endl;
carrots = carrots - 1;
cout << "I have" << carrots << "carrots." << endl;
return 0;
}
前面与上述代码相同。 之后定义carrots为25; 需要注意的是cout中加""与不加""的区别,加了后只是单纯显示其中的字符串,而不加则显示此变量代表的值。
2.3 getinfo.cpp
#include <iostream>
int main()
{
using namespace std;
int carrots;
cout << "How many carrots do you have?" << endl;
cin >> carrots;
cout << "Here are tow more";
carrots = carrots + 2;
cout << "Now you have " << carrots << "carrots." << endl;
return 0;
}
本代码添加了cin >> ,>>表示数据流的方向,从输入流向carrots。 在输出时,cout使用<<运算符将字符串插入到输出流中。 在输入时,cin使用>>运算符从输入流中抽取字符。 符号 << 和 >> 用来指示信息流的方向。