C++ Primer第一章!
#include "stdafx.h"
#include<iostream>
using namespace std;
class Sum_atob
{
public:
Sum_atob() = default;
Sum_atob(const int &a, const int &b) :a(a), b(b) {};
int getsum()
{
int sum=0;
if (a > b)
{
int tmp = a;
a = b;
b = tmp;
}
for (int i = a; i <= b; ++i)
{
sum += i;
}
return sum;
};
private:
int a = 0;
int b = 0;
};
int main()
{
cout << "hello world!" << endl; //标准输出
cerr << "wrong!"<<endl; //标准错误
clog << "runing"<<endl; //log信息
cin.ignore(); //标准输入
std::cout << "Enter two numbers:" << endl;
int v1=0, v2(0); //函数内内置类型要初始化,否则会导致未定义。
cin >> v1 >> v2;
cout << "The sum of " << v1 << " and " << v2 << " is " << v1 +v2 << endl;;
cin.ignore(); //为什么此处失效了?
int sum = 0, val = 1;
while (val <= 10)
{
sum += val;
++val;
}
cout << "Sum of 1 to 10 inclusive is " << sum << endl;
cin.ignore();
int sum_for = 0;
for (int val_for = 1; val_for <= 10; ++val_for)
{
sum_for += val_for;
}
cout << "Sum of 1 to 10 inclusive is " << sum_for << endl;
cin.ignore();
cout <<"Sum of 1 to 10 inclusive is "<< Sum_atob(1, 10).getsum() << endl;//通过类实现1到10累加。
int sum_no_limit = 0, value = 0;
while (cin >> value) //监测输入流的状态,如果有效则保持循环
{
sum_no_limit += value;
}
cout << "Sum is " << sum_no_limit << endl;
cin.ignore();
int currval = 0, val_next = 0;
if (cin >> currval)
{
int cnt = 1;
while (cin>>val_next)
{
if (val_next == currval)
++cnt;
else
{
cout << currval << " occurs " << cnt << " times" << endl;
currval = val_next;
cnt = 1;
}
}
cout << currval << " occurs " << cnt << " times" << endl;
}
cin.ignore();
return 0;
}
//类型是程序设计的基本概念,不仅定义了数据的内容,也定义了数据的运算方法,例如int类型,为内置类型。
//程序所处理的数据都保存在变量中,而每个变量都有自己的类型。定义形式,int i=0;
//可以在命令行对cpp进行编译(开始-VC工具-x64 Native Tools Command Prompt for VS 2017 Preview-cl /EHsc chapter-1.cpp)
//endl为操纵符,用于结束当前行,并将缓冲区内容刷到设备中。
//std为命名空间,标准库定义的所有名字都在命名空间std中,使用形式std::cout/using namespace std。
第一章主要在于领入门,通过各个小程序展示C++的简单应用,同时串着讲解部分知识点。