while基本内容没啥好说的跟其他的语言一个样
主要属下延时循环的注意:
#include <iostream>
#include <ctime>
int main()
{
using namespace std;
cout << "Enter the delay time, in seconds: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC;
cout << "starting\a\n";
clock_t start = clock();
while(clock() - start < delay)
;
cout << "done \a\n";
return 0;
}
再说下 类型别名:
dowhile也不记了 C咋样他就咋样 java咋样他就咋样 python咋样他就咋样 javascript咋样他就咋样 反正其他人咋样他就咋样(啰嗦)
记下基于范围的for循环(c++11)
格式: for( type x : 数组或容器类)
比如 for(double x: {1.1, 2.3, 3.8888, 6.33333333333}){cout << x << endl; }
关于文本输入的循环
如果循环中使用cin>> 的话 则默认会将空格和换行符省略掉 如果用cin.get(char)的话则不会省略。
在这里 cin.get()我们知道有另外两个变种了
cin.get(),cin.get(name, size) get.(char)
第一个只是获取输入的字符, cin.get(name, size)获取指定字符数组的指定长度。cin.get(char)获取某个char变量的字符。
这就是传说中的函数重载
文件尾条件
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch);
while(cin.fail() == false)
// 或者while()中使用这几个作为判断条件。!cin.fail(),cin,cin.get(ch)
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << " characters read\n";
return 0;
}
WIN10下也是ctrl+z
在iostream中海油一个EOF的常量 表示-1 代表了输入的结尾。 但是 不是所有系统的结尾都算是用-1表示 也有可能是没有字符(比如WIN10)另外 如果将ch的类型声明成int 就需要强制类型转换成char才能put或者cin.get()
这句话我讲不好 因为他是有一大段来讨论这个文件尾的问题。嗯。。我感觉有点啰嗦了 所以 我就总结了一下 如果有兴趣的话可以参考书的第157-18页
先上修改的代码:
#include <iostream>
int main()
{
using namespace std;
int ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
while((ch = cin.get()) !='#')
{
cout.put(char(ch));
++count;
}
cout << endl << count << " characters read\n";
return 0;
}
这段代码在WIN10系统下 按ctrl+z 是会进入无限循环
关于文本输入的循环最后:
二维数组的嵌套循环: 直接上代码吧
#include <iostream>
const int Cities = 5;
const int Years = 4;
int main()
{
using namespace std;
const char* cities[Cities] =
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
int maxtemps[Years][Cities] =
{
{96, 100, 87, 101, 105},
{96, 98, 91, 107, 104},
{97, 101, 93, 108, 107},
{98, 103, 95, 109, 108}
};
cout << "Maximum temperatures for 2008 - 2011\n\n";
for (int city = 0; city < Cities; ++city)
{
cout << cities[city] << ":\t";
for (int year = 0; year < Years; ++year)
{
cout << maxtemps[year][city] << "\t";
}
cout << endl;
}
return 0;
}
最后 发一个总结: