目录
goto语句
goto 语句一个很好的作用是退出深嵌套例程。
示例代码段
for(...)
{
for(...)
{
while(...)
{
if(...)
goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
goto label;
...
label: statement;
虽然goto语句在程序中显得十分便利,但并不建议过多使用 goto ,对于简短的代码,能十分明了的知晓各段的逻辑分布,但对于较长的代码,使用goto弄不好会使模板混乱,且在团队合作中不利于阅读解析。goto完全可以由其他代替,例如try.....catch/finally,最通俗易懂的笨方法就是用break一点点的跳。
替代方法
try....catch
try {
if (failed)
{
throw Exception;//throw停止运行
}
if (failed)
{
throw Exception;
}
if (faled)
{
throw Exception;
}
} catch (Exception)
{
.........
}
try.....finally
try {
if (failed)
{
return;
}
if (failed)
{
return;
}
if (failed)
{
return;
}
} finally {
.............
}
同时相当于
if (failed) {
goto goust;
}
if (failed) {
goto goust;
}
if (failed) {
goto goust;
}
goust:
..............
setw
用于设置字段的宽度,就是指一个字可能本身用不了这麽多,但为了对齐,还是要规定站的地方大小的。
setw(int n)只是对直接跟在<<后的输出数据起作用,而在之后的<<需要在之前再一次使用setw;右对齐,n个字符宽度。
可以使用setiosflags(ios::left)设置为左对齐输出,可以使用setfill('char x')使用x来填充空下的空格;
例如:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char *str="hello";
cout<<setw(10)<<setiosflags(ios::left)<<setfill('*')<<str<<endl;
cout<<setw(10)<<setiosflags(ios::right)<<setfill('*')<<str<<endl;
cout<<setw(10)<<setfill('*')<<str<<endl;
system("pause");
return 0;
}
输出
srand
随机数发生器的初始化函数 ,void srand(unsigned seed);
它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。如: srand(1); 直接使用 1 来初始化种子。
不过为了防止随机数每次重复,常常使用系统时间来初始化,即使用 time 函数来获得系统时间,它的返回值为从 00:00:00 GMT, January 1, 1970 到现在所持续的秒数,然后将 time_t 型数据转化为(unsigned)型再传给 srand 函数,即: srand((unsigned) time(&t));
还有一个经常用法,不需要定义time_t型t变量,即: srand((unsigned) time(NULL)); 直接传入一个空指针,因为你的程序中往往并不需要经过参数获得的t数据。
举例:
rand
#include <iostream>
#include<Windows.h>
#include <time.h> /*用到了time函数,所以要有这个头文件*/
#define MAX 10
using namespace std;
int main( )
{
int number[MAX] = {0};
int i;
srand((unsigned) time(NULL)); /*播种子*/
for(i = 0; i < MAX; i++)
{
number[i] = rand() % 100; /*产生100以内的随机整数*/
cout<<number[i];
cout<<endl;
}
Sleep(10000);
return 0;
}
宏定义中定义一个random(int number)函数
#include <iostream>
#include<Windows.h>
#include<time.h>
#define random(x)(rand()%x)//宏观定义
using namespace std;
int main()
{
srand((int)time(0));//部署随机种子
for (int i = 0; i < 10; i++)
{
cout << random(100) << endl;
}
Sleep(10000);
return 0;
}