1. 包含iostream头文件
2. cout 输出
cin 输入
<< 输出运算符
>> 输入运算符
注:以上均属于std空间
3. 注释
// 单行注释,换行符结束
/* ........... */ 中间全部注释
4. while(condition)
{
statement
}
#include <iostream>
int main()
{
int minnum = 0, maxnum = 0,i =0;
std::cout << "please enter two number " << std::endl;
std::cin >> minnum >> maxnum;
if (minnum > maxnum)
while (minnum >= maxnum)
{
i = minnum;
std::cout << "the numbers of min to max is" << i << std::endl;
--minnum;
}
else
{
while (maxnum >= minnum)
{
i = maxnum;
std::cout << "the numbers of min to max is" << i << std::endl;
--maxnum;
}
}
return 0;
}
5. for循环
for(init-statement,condition,expression)
#include <iostream>
int main()
{
int min = 0,max = 0,i = 0;
std::cout << "please enter two numbers" << std::endl;
std::cin >> min >> max;
if (min >= max)
{
for (min; min >= max; --min)
{
i = min;
std::cout << "the numbers of min to max is" << i << std::endl;
}
}
else
{
for (max; max >= min; --max)
{
i = max;
std::cout << "the numbers of min to max is " << i << std::endl;
}
}
return 0;
}
注:while适用于循环次数不知,条件已知
for适用于循环条件已知。
ctrl+z输入endl符。
6.读取数量不定的输入数据
while(cin >> value)
#include <iostream>
int main()
{
int sum = 0, value = 0;
std::cout << "enter a little numbers" << std::endl;
while (std::cin >> value)
sum += value;
std::cout << "the sun of numbers is " << sum << std::endl;
//system("pause");
return 0;
}
注:常见编译器错误
1.语法错误.
2.类型错误
3.声明错误
7. if语句
每个值连续出现多少次
#include <iostream>
int main()
{
int currVal = 0, val = 0;
if (std::cin >> currVal)
{
int cnt = 1;
while (std::cin >> val)
{
if (val == currVal)
++cnt;
else
{
std::cout << currVal << "occurs " << cnt << "times" << std::endl;
currVal = val;
cnt = 1;
}
}
std::cout << currVal << "occurs" << cnt << "times" << std::endl;
}
return 0;
}
8. 类
数据结构(data structure)
类(class)
注:对于不属于标准库的头文件,使用“”来引用
#include <iostream>
#include<1\Sales_item.h>
int main()
{
Sales_item book;
std::cin >> book;
std::cout << book << std::endl;
return 0;
}
成员函数:#include <iostream>
#include<1\Sales_item.h>
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn())
{
std::cout << item1 + item2 << std::endl;
return 0;
}
else
{
std::cerr << "something is wrong" << std::endl;
return -1;
}
}
其中,item1.isbn()即成员函数,通常使用.运算符来调用,其中,左侧运算对象必须是一个类类型成员,右侧运算对象必须是该类型的一个成员名,运算结果为右侧运算对象指定的成员。并且一般会使用调用运算符()来完成调用,