1.循环
经验:规则基本和java保持一致。
1.1.for循环
#include <iostream>
using namespace std;
int main()
{
//和java语法一样,如果内部只有一行,大括号可以省略;
//i的定义可以在for循环之前定义。
for(int i=0; i< 10; i++) {
cout << i << endl;
}
return 0;
}
1.2.while循环
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i != 5) {
cout << i << endl;
i++;
}
return 0;
}
延迟循环控制
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
float sec = 5;
clock_t d = sec * CLOCKS_PER_SEC;
cout << d << endl;
clock_t s = clock();
while (clock() - s < d)
;
cout << s << endl;
return 0;
}
1.3.do while循环
#include <iostream>
using namespace std;
void testDoWhile();
int main()
{
int a = 1;
do{
cout << a;
if(a != 9) {
cout << "...";
}else{
cout << endl;
}
a++;
}while(a != 10);
return 0;
}
结果:
1...2...3...4...5...6...7...8...9
2.if语句和逻辑运算符
if…else语句和java的if …else语句,没有任何的区别。
关于逻辑运算符
首选 | 代用 |
---|---|
&& | and |
&= | and_eq |
& | bitand |
| | bitor |
~ | compl |
! | not |
!= | not_eq |
|| | or |
|= | or_eq |
^ | xor |
^= | xor_eq |
{ | <% |
} | %> |
[ | <: |
] | :> |
# | %: |
## | %:%: |
3.输入输出流
3.1.输出流
写入文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream out; // ofstream == out file stream
out.open("/home/farton/tmp/test.txt");//默认会新建一个文件,如果存在会覆盖源文件
out << "hahaha";
out.close();//记得关闭输出流
return 0;
}
3.2.输入流
读取文件
1.文件内容:
hahaha0
asd1
asd2
asd3
2.代码
#include <iostream>
#include <fstream>
#include <cstdlib> // use by exit(EXIT_FAILURE);程序退出
#include <cstring>
using namespace std;
int main()
{
ifstream in;// ifstream == in file stream
in.open("/home/farton/tmp/test.txt");
if(!in.is_open()){
exit(EXIT_FAILURE);
}
string allValue;
string value;
do{
in >> value; //将每一行的数据进行赋值
allValue += value;
}while(in.good());// 检测文件内是否还有下一行
cout << allValue << endl;
in.close();// 关闭文件流
return 0;
}
3.结果
hahaha0asd1asd2asd3asd3
4.函数
4.1.基础写法
方法原型:将方法信息告诉解释器
#include <iostream>
using namespace std;
void test(); //方法原型:将方法信息告诉解释器
int main()
{
test();//方法调用
return 0;
}
void test(){
//方法定义
cout << "test" << endl;
}
4.2.函数中传递数组
数组的指针int * array
和数组int array[]
,在定义函数的参数时是相同的,都是指的是地址。
如:
void test(const int arr[]){
for(int i = 0; i < arr.length; i++) {
cout << arr[i] << endl;
}
}
其中,const相当于java中的final,声明在方法中数组arr不会发生修改等操作。