C++的学习之旅——循环

目录

一、for循环

二、while循环

三、do while循环

四、基于范围的for循环

五、循环和文本输入

1、使用原始的cin进行文本输入

2、使用cin.get(char)进行补救

3、使用哪一个cin.get()

4、文件尾条件

 六、嵌套循环和二维数组


一、for循环

与C语言一样,C++for循环一般格式为:

for(initialization;test-expression;update-expression)
{
    body;
}

如:
int i;
int sum=0;

for(i=0;i<5;i++)
{
    sum+=sum;
}

在C基础上,initialization只能是表达式,其中的变量需要在for之前定义,不过C++在C的基础上添加了一项特性,支持在for循环控制部分声明变量

for(int i=0;i<5;i++)
{
    body;
}

 变量i在for执行完后消失

二、while循环

while循环是没有初始化和更新部分的for循环,它只有测试条件和循环体:

while(test-condition)
{
    body
}

三、do while循环

do while是出口条件循环,这种循环先执行循环体,再判定测试表达式

do{
    body
}while(test-expression)

四、基于范围的for循环

C++11新增了一种循环:基于范围的for循环,这简化了对数组(或容器类,如vector和array)的每个元素执行相同的操作 

double prices[5]={4.99,10.99,6.87,7.99,8.49};
for(double x : prices)
    cout<<x<<std::endl;

 其中,x最初表示数组prices的第一个元素。显示第一个元素后,不断执行循环,而x依次表示数组的其他元素。因此,上述代码显示全部5个元素,每个元素占一行。而要修改数组元素,需要使用不同的循环变量语法:

for(double &x:prices)
    x=x*0.80;

 符号&表明x是一个引用变量,这种声明让接下来的代码可以修改数组的内容,而第一种语法不能。

另外,还可以使用基于范围的for循环和初始化列表

for(int x:{3,5,2,8,6})
    cout<<x<<" ";
cout<<std::endl;

五、循环和文本输入

1、使用原始的cin进行文本输入

使用循环可以逐字符地读取来自文件或键盘地文本,然后使用某个特殊字符——有时候被称为哨兵字符,将其作为停止字符。

#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	char ch;
	int count=0;
	cout<<"Enter characters;enter # to quit:"<<endl;
	cin>>ch;
	while(ch!='#')
	{
		cout<<ch;
		++count;
		cin>>ch;
	}
	cout<<endl<<count<<"characters read\n";

	return 0;
}

 

由输入输出可知,cin忽略空格和换行符。因而输入中的空格没有被回显。另外,发给cin的输入会被缓冲,意味着只有用户在按下回车键后,输入内容才会被发送给程序。而在#可以继续输入字符,但是按下回车键后,输入内容发送给cin,程序在遇到#时结束对输入的处理,跳出循环,所以没有显示#后面的内容。

2、使用cin.get(char)进行补救

 cin忽略空格和换行符,因而当需要统计空格时,可以使用cin.get(char),即使是空格也会将其赋给ch。可以使用cin.get(ch)代替cin<<ch。

3、使用哪一个cin.get()

在之前,我们使用了如下几种版本cin.get()

cin.get(name,ArSize);
cin.get(ch);
cin.get();

 在C语言,如果函数接受char指针和int参数,则使用该函数时,不能只传递一个参数,但在C++中可以,因为C++支持被称为函数重载的OPP特性。函数重载允许创建多个同名函数,条件是参数列表不同,如使用cin.get(name,ArSize),则编译器将找到使用char*和int作为参数的cin.get()版本。

4、文件尾条件

在前面代码中,使用诸如#作为输入结束存在一定缺陷,可以使用检测文件尾条件(EOF)(具体定义可以自行查找)来避免这种缺陷,文件尾条件用于输入是文件的情况,用来检测文件是否停止输入,不过现在很多操作系统允许通过键盘来模拟文件尾条件。很多PC编程环境都将Ctrl+Z视为模拟的EOF,但是具体细节(是否需要按下回车键等) 各不相同。

使用键盘输入模拟EOF,检测到EOF后,cin将两位(eofbit和failbit)都设置为1.可以通过成员函数eof()和fail()来查看eofbit和failbit是否被设置,被设置则返回bool值true,否则返回false。

#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	char ch;
	int count=0;
	cout<<"Enter characters;enter # to quit:"<<endl;
	cin.get(ch);
	while(cin.fail()==false)
	{
		cout<<ch;
		++count;
		cin.get(ch);
	}
	cout<<endl<<count<<"characters read\n";

	return 0;
}

 

 由程序结果可见,在输入agkhgjkw和dmgcvhkbj字符串后,输入Ctrl+Z回车之后,程序停止输入。

另外,还有一个版本的cin.get()可以用于判别EOF是否被检测到,该cin.get()成员函数返回输入中的下一个字符。可以这样使用它:

ch=cin.get();

当检测到EOF时,会返回一个用符号常量EOF表示的特殊值,该常量是在头文件iostream中定义的。通常,EOF被定义为-1。ASCLL码没有-1的字符,不过不需要知道实际值,只需在程序中使用EOF即可。  

#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	char ch;
	int count=0;
	cout<<"Enter characters;enter # to quit:"<<endl;
	ch=cin.get();
	while(ch!=EOF)//如果ch是一个字符,循环将显示它,如果ch为EOF,循环将结束
	{
		cout<<ch;
		++count;
		ch=cin.get();
	}
	cout<<endl<<count<<"characters read\n";

	return 0;
}

 六、嵌套循环和二维数组

经常使用for循环的嵌套来处理二维数组,二维数组的深入可自行搜索,其定义以及初始化参考如下:

int maxtemps[4][5]
{
    {96,100,87,101,105};
    {96,98,91,107,104};
    {97,101,93,108,107};
    {98,103,95,109,108};
}//创建4行5列的二维数组

下面使用嵌套循环输出二维数组 

#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

const int Cities=5;
const int Years=4;

int main(int argc, char** argv) {
	
	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<<"Maximun temperatures for 2008-2011\n\n";
	for(int city=0;city<Cities;city++)//使用for循环双嵌套输出二维数组
	{
		cout<<cities[city]<<":\t";
		for(int year=0;year<Years;year++)
		{
			cout<<maxtemps[year][city]<<"\t";
		}
		cout<<endl;
	}
	return 0;
}

C++的学习笔记持续更新中~

要是文章有帮助的话,就点赞收藏关注一下啦!

感谢大家的观看

欢迎大家提出问题并指正~

猜你喜欢

转载自blog.csdn.net/qq_47134270/article/details/128613319