5.1,5.2

5.1 for循环

c++对for循环的调整。允许

for(int i=0;i<5;i++)这样的情况出现

这样做的优点是变量i只出现在for循环中。

a++,++a;

a++表示使用a的当前值,然后将a加1;

++a表示先将a+1,然后使用新的值。

 

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int main()
 5 {
 6     string word;
 7     cout<<"enter a word";
 8 
 9     cin>>word;
10 
11     for(int i=0,j=word.size()-1;i<j;i++,j--)
12     {char temp=word[i];
13     word[i]=word[j];
14     word[j]=temp;
15     }
16     cout<<word;
17     return 0;
18 }

程序将一个字符串按反向存储并输出,

size()用于返回字符串的大小,word.size();

5.1.14 C风格字符串的比较

不能用关系运算符比较字符串的大小。

例如:字符串数组word,

word=“mata”;是错误的

以为数组名是地址,而引号之中的字符串常量也是地址。

比较字符串大小用函数:strcmp(),它的参数是地址,因此参数可以是指针、字符串常量、字符数组名。

如果字符串相等返回0;

如果第一个字符串大于第二个,返回负值;

如果第一个字符串小于第二个,返回正值。

可以用关系运算符比较字符,因为字符实际上是整数。

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 int main()
 5 {
 6     char word[5]="?ate";
 7     for(char ch='a';strcmp(word,"mate");ch++)
 8     {
 9         cout<<word<<endl;
10         word[0]=ch;
11     }
12     return 0;
13 }

5.1.15比较string类的字符串

 

因为类函数重载了这些运算符,所以可以使用关系运算符对string类进行比较。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int main()
 5 {
 6     string word="?ate";
 7     for(char ch='a';word!="mate";ch++)
 8     {
 9         cout<<word<<endl;
10         word[0]=ch;
11     }
12     return 0;
13 }

5.2while循环

延时循环

使用头文件<ctime>;

CLOCKS_PER_SEC,该变量等于每秒钟包含的系统单位时间数。

clock_t为clock()返回类型的别名。

 1 #include<iostream>
 2 #include<ctime>
 3 int main()
 4 {
 5     using namespace std;
 6     cout<<"enter the delay time ,in seconds";
 7     float sec;
 8     cin>>sec;
 9     clock_t delay=sec*CLOCKS_PER_SEC;
10     cout<<"starta
";
11     clock_t start=clock();//clock()返回程序开始执行后所用的系统时间
12     while(clock()-start<delay)
13     {};
14     cout<<"done
";
15     return 0;
16 }
原文地址:https://www.cnblogs.com/taoxiuxia/p/4143023.html