1.2最简单的C++程序
输出一行字符:“This is C++ program.”。
#include <iostream>
using namespace std;
int main()
{cout<<"This is a C++ program.\n";
getchar();
return 0;
}
【问题】然后程序一闪而过。
【原因】主要是因为程序在运行后发现没问题就直接退出,输出太快。
【解决】输入:system(“pause”) ;——让程序暂停一下,然后按任意键继续用于看运行结果,避免程序一闪而过。
相同的我们还可以用getchar()。
#include <iostream> //用cout输出时需要用此头文件
using namespace std; //使用命名空间std
int main()
{cout<<"This is a C++ program.\n"; //用C++的方法输出一行
system("pause"); //暂停的意思,等待用户信号/或者使用getchar()
return 0;
}
求a和b两个数之和
//求两数之和 (本行是注释)
#include <iostream> //预处理命令
using namespace std; //使用命名空间std
int main() //主函数首部
{ //函数体开始
int a,b,sum; //定义变量
cin>>a>>b; //输入语句
sum=a+b; //赋值语句
cout <<"a+b="<<sum <<endl; //输出语句(endl是end line的缩写,表示行结束,与“\n”作用相同)
system("pause");
return 0; //如程序正常结束,向操作系统返回一个零值
}
【问题】此处的system(“pause”); 不能直接用getchar();替换。
【原因】因为你键盘中敲入的键不会立马读取,而是到一个叫缓冲区的地方。cin和getchar都是从缓冲区读取你的输入,cin遇到回车就停下了,但是并不把回车舍去,也就是回车依旧在缓冲区内。在用getchar就会读取到回车,也就结束了,所以才会闪退。
【解决】使用getchar();前加一个fflush(stdio);——清除一个流,即清除文件缓冲区,当文件以写方式打开时,将缓冲区内容写入文件。
输入两个数x和y,求两个数中的大者
#include <iostream>
using namespace std;
int main()
{int max(int x,int y); //对max函数作声明
int a,b,c;
cin>>a >>b;
c=max(a,b); //调用max函数
cout<<"max="<<c <<endl;
system("pause");
return 0;
}
int max(int x,int y) //定义max函数
{int z;
if(x>y)z=x;
else z=y;
return(z);
}
包含类的C++程序
#include <iostream>
using namespace std;
class Student //声明一个类,类名为Student
{private: //以下为类的私有内容
int num; //私有变量num
int score; //私有变量score
public: //以下为类中公用部分
void setdata() //定义公用函数setdata
{cin >>num; //输入num的值
cin >>score; //输入score的值
}
void display() //定义公用函数diaplay
{cout <<"num="<<num <<endl; //输出num的值
cout <<"score="<<score <<endl; //输出score的值
};
}; //类的声明结束
Student stud1,stud2; //定义stud1和stud2为Student类的变量,称为对象
int main() //主函数首部
{stud1.setdata(); //调用对象stud1的setdata函数
stud1.display();
stud2.setdata();
stud2.display();
system("pause");
return 0;
}
运行结果:
01 90
num=1
score=90
02 100
num=2
score=100
[1]谭浩强 C++面向对象程序设计